Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Consider a table as `table2`, i like to add a `trigger` on this table `update` as
```
select Num into num from table1 where ID=new.id;
BEGIN
DECLARE done int default false;
DECLARE cur1 CURSOR FOR select EmailId from users where Num=num;
DECLARE continue handler for not found set done = true;
OPEN cur1;
my_loop: loop
... | I'm against that solution. Putting the load of sending e-mails in your Database Server could end very bad.
In my opinion, what you should do is create a table that queues the emails you would want to send and have a process that checks if there are emails to be sent and send them if positive. | As everyone said, making your database to deal with E-Mails is a bad idea. Making your database to write an external file is another bad idea as IO operations are time consuming compared to database operations.
There are several ways to deal with your issue, one that I like: Having a table to queue up your notificatio... | Send email from MySQL trigger when a table updated | [
"",
"mysql",
"sql",
"email",
"triggers",
"sendmail",
""
] |
I have table `tags`, and I also want to count from table `questions` all rows who have in their column `tags` the `tag` name LIKE from the `tags` database.
Combine this two queries I mean:
```
SELECT * FROM tags WHERE 1 SELECT COUNT(*) FROM `questions` WHERE `tags`
LIKE '%(the tag column from tags table)%'
``` | ```
SELECT t.name, Count(*) FROM tags t
join questions q on t.tag_id = q.tag_id
Where t.name like '%(the tag column from tags table)%'
group by t.name
```
If you are looking for `Batches of SQL Statements`
then you can do something like this by placing `;` at the end of first query
```
SELECT * FROM `tags` WHERE 1 ;... | You must have at least one field in common, use it to relate the tables:
```
SELECT t.name,q.COUNT(*) FROM questions q, tags t WHERE `tags`
LIKE t.name and q.tag=t.name;
``` | How to query two tables in one query | [
"",
"sql",
""
] |
I am currently making use of the code below:
```
ALTER PROCEDURE [dbo].[sp_TidyBasket]
@ReferenceNumber VARCHAR
AS
BEGIN
BEGIN TRANSACTION
DECLARE
@GUID VARCHAR,
@ErrorCode INT
--Get the First Reference Number of a basket item being duplicated
SET @GUID = (SELECT TOP 1 MIN(idx6)
... | Try with this:
```
ALTER PROCEDURE [dbo].[sp_TidyBasket]
@ReferenceNumber VARCHAR
AS
BEGIN TRY
BEGIN TRANSACTION;
WITH cte
AS ( SELECT idx6 ,
ROW_NUMBER() OVER ( PARTITION BY Idx37 ORDER BY ( SELECT ( 1 ) ) ) AS RN
... | Try this. No loop required.
```
DELETE FROM iwfAccountOpening WHERE Idx6 in (SELECT MIN(idx6)
FROM iwfAccountOpening
WHERE Idx29 = @ReferenceNumber
GROUP BY Idx37
HAVING COUNT(*) > 1) and Idx29 = @ReferenceNumber
``` | User Defined Value for Deleting Duplicates in Stored Procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
Is there a way to GROUP BY a part of a string....
I wanted to create a SQLFIDDLE but they seem to have to serverproblems, so I have to make it visible here....
This would be the data...
```
CREATE TABLE tblArticle
(
id int auto_increment primary key,
art_id varchar(20),
art_name varchar(30),
... | In order to group, you must specify which bit of the string to group by. In this case it's the first 5 characters so you would use `LEFT(art_id,5)`. This must be matched in the `SELECT` statement so you will need to modify it to read the same.
I have aliased the column to be art\_id otherwise it will be unknown:
```
S... | You could try this, It will work out where the dash is and group by properly
```
Select case when Instr(art_id, '-') = 0
then art_id
else Left(art_id, Instr(art_id, '-') - 1) end, art_name
FROM tblArticle
WHERE art_type = 'MAT'
GROUP BY case when Instr(art_id, '-') = 0
t... | SQL Select GROUP BY part of field if has a special char | [
"",
"sql",
"sqlbase",
""
] |
I have this table in my database:
```
╔════╦═══════╦═══════╗
║ id ║ Name ║ Price ║
╠════╬═══════╬═══════╣
║ 1 ║ ciao ║ 123 ║
║ 2 ║ ciao ║ 55 ║
║ 3 ║ bye ║ 43 ║
║ 4 ║ hello ║ 12 ║
║ 5 ║ ciao ║ 1 ║
║ 6 ║ ciao ║ 77 ║
╚════╩═══════╩═══════╝
```
..and i wound like to create a new view displa... | This might work (not tested) :
```
SELECT CASE
WHEN name = 'ciao' THEN 'ciao'
ELSE 'not ciao'
END as NAME,
COUNT(*)
FROM table
GROUP BY CASE
WHEN name = 'ciao' THEN 'ciao'
ELSE 'not ciao'
END
```
OR in MySQL
```
SELECT CASE
WHEN name = 'ci... | You need to map everything except `'ciao'` to `'not ciao'`, like this:
```
SELECT CASE WHEN Name!='ciao' THEN 'not ciao' ELSE Name END as Name, COUNT(*)
FROM mytable
GROUP BY CASE WHEN Name!='ciao' THEN 'not ciao' ELSE Name END
``` | SQL Query using GROUP BY Statment | [
"",
"mysql",
"sql",
"group-by",
""
] |
I have tables that look somewhat like this:
```
Table name: products
ID PRODUCT_ID TYPE PRICE ...
1 111 computer xxx
2 222 book xx
3 333 computer xxxx
----------------------------------------------------------------
Table name: pro... | If i understood you correctly, then you need all columns from `products` table and their corresponding information (if any) from `products_computer` and `products_book` tables.
If this is the scenario then I think all you need here is multiple `LEFT JOIN` SQL statements
**SQL Statements**
```
SELECT products.product... | This is possible with a [`UNION`](https://www.sqlite.org/lang_select.html#compound) statement.
```
SELECT
products.ID AS ID, products.PRODUCT_ID AS PRODUCT_ID, products.PRICE AS PRICE, products_computer.CPU AS CPU, products_computer.RAM AS RAM,
null as AUTHOR, null as YEAR_PUBLISHED
FROM products_computer
... | Compute table name to join from row value | [
"",
"sql",
"sqlite",
""
] |
I am pulling my hair out trying to figure out what I am doing wrong.
The table is very simple:
```
CREATE TABLE `icd_index` (
`icd` char(5) NOT NULL,
`core_id` int(11) NOT NULL,
`dx_order` tinyint(4) NOT NULL,
PRIMARY KEY (`icd`,`dx_order`,`core_id`),
KEY `core` (`core_id`)
) ENGINE=MyISAM DEFAULT CHARSET=ut... | Here's what is going on.
```
The SELECT COUNT (...) icd_index where icd='25000'
```
will use the index, which is a BTree separate from the data. But it scans it in this way:
1. Find the first entry having icd='25000'. This is almost instantaneous.
2. Scan forward until if finds a change in icd. This will scan in the... | Thanks to all above for your help. Given the above advice, I totally rebuilt the database like so:
1. I convinced the server admin to increase my RAM to 6G.
2. I switched all tables to InnoDB with an ASCII character set.
3. When I moved the data from MyISAM to InnoDB, I sorted all of the data in the order of the cover... | MySQL MyISAM slow count() query despite covering index | [
"",
"mysql",
"sql",
""
] |
**EDIT**: After looking at some of the answers here and hours of research, my team came to the conclusion there was most likely no way to optimize this further than the 4.5 seconds we were able to achieve (unless maybe with partitioning on offers\_clicks, but that would have some ugly side-effects). Eventually, after l... | This is your query:
```
SELECT count(distinct u.id) AS count_1
FROM offers_clicks oc JOIN
users u
ON oc.user_id = u.id
WHERE u.country IN ('US') AND u.last_active > '2015-02-26' AND
oc.date > '2015-02-14' AND
oc.ranking_score > 0.24 AND oc.ranking_score < 3.49;
```
First, instead of `count(disti... | ```
SELECT count(distinct u.id) AS count_1
FROM users u
STRAIGHT_JOIN offers_clicks oc
ON oc.user_id = u.id
WHERE
u.country IN ('US')
AND u.last_active > '2015-02-26'
AND oc.date > '2015-02-14'
AND oc.ranking_score > 0.24
AND oc.ranking_score < 3.49;
```
Make sure you have index on users ... | Optimizing slow MySQL select query | [
"",
"mysql",
"sql",
"query-optimization",
""
] |
I need to select all entries that do not start with a number between 1-9.
**Example Entries**:
* 6300 Dog Lane
* Kitty Drive
* 500 Bird Chrest
* 800 Tire Road
* Johnson Ave
* Park Ave
**So if I ran a query on the above, I would expect**:
* Kitty Drive
* Johnson Ave
* Park Ave
The table is called `objects` and the ... | Try this:
```
SELECT DISTINCT name, location FROM object
WHERE substring(location, 1, 1)
NOT IN ('1','2','3','4','5','6','7','8','9');
```
or you have to add `NOT LIKE` before every number:
```
SELECT DISTINCT name, location FROM object
WHERE location NOT LIKE '1%'
OR locati... | You can use the following stntax:
```
SELECT column FROM TABLE where column NOT REGEXP '^[0-9]+$' ;
SELECT DISTINCT name, location FROM object
WHERE location NOT REGEXP '^[0-9]+$' ;
``` | Select query or select entries that don't start with a number - MySQL | [
"",
"mysql",
"sql",
"select",
""
] |
I created a table called employee
```
CREATE TABLE employee(
id INT,
name VARCHAR(50),
credit_card_number VARCHAR(20),
expr_date CHAR(6),
PRIMARY KEY(id)
)
```
And then I have a table that stores the credit cards information
```
CREATE TABLE credit_card (
credit_card_number VARCHAR(20),... | It should look like this:
```
INSERT INTO credit_card(credit_card_number, expr_date, o_datetime)
SELECT credit_card_number, expr_date, CURRENT_TIMESTAMP
FROM employee;
```
You need to define the 3rd column of your insert, in this case, `CURRENT_TIMESTAMP` for `o_datetime`.
* [SQL Fiddle Demo](http://www.sqlfiddle.co... | First, you should never store unencrypted credit card numbers in a database. This is an invitation for someone to "borrow" the numbers. You can hash them or store them in some other fashion to prevent unauthorized access.
The problem with your statement is the `o_datetime` component. The default value can go in the `s... | MySQL: Is there a way to insert values from one table to another? | [
"",
"mysql",
"sql",
"insert-select",
""
] |
Given a table like:
```
Employee (emp_no, emp_fname, emp_lname, emp_salary, job_title)
```
How to write a query that for each employee calculates the difference
between his/her salary to the average salary of his/her job group?
To get the avg. Salary for each group I use:
```
Select job_title, avg(emp_salary) as av... | Depending on which database you are using, you may be able to arrive at this more efficiently using either window functions or CTEs. But a SQL solution that should work on pretty much any SQL-based database you could use would look like:
```
SELECT a.emp_no,
a.emp_fname,
a.emp_lname,
... | Alternatively, you can also use a subquery to get the answer to this question as below.
Step1: Create a query to get the average of the employee's salary.
Step2: Use query created in step-1 as a subquery and subtract it from the main query's
salary column.
Code :
`SELECT first_name,last_name,salary ,salary-(SELECT A... | Calculates the difference between employee salary and the average salary of job group | [
"",
"sql",
""
] |
I am trying to count the number of records for each user:
```
SELECT count(userID) as countOfRecords FROM (select distinct userID from `table`)
```
I get the error: *Every derived table must have its own alias* What am I doing wrong? | You can use `GROUP BY`
```
select userID, count(*) as countOfRecords
from table
group by userID
``` | You don't need a derived table, you can just do count(distinct):
```
SELECT count(distinct userID) as countOfRecords
FROM `table`
```
**Edit:** When I see Philip Fourie's answer I realize I perhaps didn't give the complete answer... See his `GROUP BY` solution as well. | Counting records SQL | [
"",
"sql",
""
] |
I have 2 fields in my SQL table. One has 5 digits (ex: 12345) and the 2nd field has 2 digits (ex: 99) and I need to know if there is a way to take the LAST digit from the first field and push it to the beginning of the 2nd field. So the first field would be 1234 and the 2nd field would be 599 ??? | ```
UPDATE YourTable
SET Column2 = RIGHT(Column1, 1) + COALESCE(Column2, ''),
Column1 = LEFT(Column1, LEN(Column1)-1)
WHERE COALESCE(LEN(Column1), 0) > 1;
``` | Here is a "typical" way to do this.
```
update t
set col1 = left(col1, length(col1) - 1),
col2 = concat(right(col1, 1), col2);
```
The exact details depend on the database.
Notes:
* This sort of assumes the values are stored as strings, although the logic will convert back and forth from numbers.
* The ... | Update 2 fields - push last digit from 1 field to the beginning of another field | [
"",
"sql",
""
] |
I am trying to copy one table to another in oracle changing the value of one of the fields.
Lets say Tables Original and Temp, so I normally would use this SQL bellow:
```
Insert into Original Select * from Temp where site = 1
```
The problem is that now my Original table already has the site 1 so I need to copy the... | I wrote simple PLSQL procedure, code below. It generates insert string to output,
if these suits you, you can copy/paste them and run manually or you can uncomment
line near end and inserts will be done automatically. Tested on sample data, worked fine.
Procedure operates on columns found in `user_tab_columns`. At fir... | You can try the below query
```
INSERT INTO Original select '2' from Temp union all select * from Temp where site=1;
```
Explanation :
I) value '2' will be inserted into first column named "site"
II)Column values field1,field2,field3 from Temp table will be insserted to field1,field2,field3 of original table | Insert a table inside another with one field different | [
"",
"sql",
"oracle",
"insert",
""
] |
OK, so this one has had me ripping my hair out for hours. I feel like there is something obvious I am overlooking.
I have 2 tables, **service** and **brand**
```
service
-------
id
brand
brand
-----
id
brandName
```
So service.brand can be any of these:
```
Blank
"Other"
Integer (matches brand.id)
String (match... | ```
select
s.*,
CASE
WHEN b_id.brandName IS NOT NULL THEN b_id.brandName
WHEN b.brandName IS NOT NULL THEN b.brandName
ELSE s.brand
END as bname
from
service s
LEFT JOIN brand b_id
ON CAST(s.brand AS UNSIGNED) = b_id.id
LEFT JOIN brand b
ON s.brand = b.brandName
``` | You are using an old style `inner join`:
```
from service s, brand b
where s.brand = b.brandName or ...
```
More clearly written like:
```
from service s
inner join brand b on s.brand = b.brandName or ...
```
In the newer form, the problem immediately stands out. An `inner join` filters out unmatched rows. Use a `... | MySQL SQL Select Query with Multiple Sub-Selects | [
"",
"mysql",
"sql",
"subquery",
""
] |
I need some help as I am learning SQL so I am at a beginner level. I am using SQL Server 2008 R2.
My question is: I want to (add) sum up a column that have mix values of `varchar` and `decimal`. I want to ignore the `varchar` values and sum only `decimal`. My column is like this:
```
Column1
-------
0.1
Z
0.4 ... | Simply use `WHERE` clause with `CAST`:
```
SELECT SUM(Cast(Column1 as numeric(10,2))) as Total
FROM TABLE_Name
Where IsNumeric(Column1) = 1
```
Result:
```
TOTAL
4.7
```
Sample result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/ca2eb/2).
**EDIT:**
As @funkwurm pointed out, the column has a chance to have the... | Why not using TRY\_CONVERT:
```
SELECT SUM(TRY_CONVERT(float,Column1) AS Total
FROM TABLE_Name
```
Shortest query and easy to read! TRY\_CONVERT returns NULL if conversion fails (e.g. if there are text values in Column1)
This Functions exists since SQL Server 2012 (i think).
**@Jim Chen:**
Isnumeric is a bit trick... | SQL Server : SUM () for only numeric values, ignoring Varchar values | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I am new to SQL Server and I don't know how to word this question. I have feeling this might be repeated. If you know it please flag it as duplicate. I will explain with data what I am trying to achieve
Table data - `sometable`
```
ID TKID Status DateTimeStamp RunMin
--------------------------------... | If you modify your `ROW_NUMBER() PARTITION` to `order by DateTimeStamp desc`, then the latest row for each `tkid` will be given `rn=1`, thus giving you the latest status for each `tkid`. You then simply have to `SELECT` rows where the `rn = 1` and the `Status = 'Start'` to get your desired output:
```
select * from
(s... | Lot of ways to do this, one of them is below:
```
SELECT T.*
FROM SOMETABLE T
JOIN (SELECT MAX(DATETIMESTAMP) MAXTIME, TKID
FROM SOMETABLE
GROUP BY TKID) SRC
ON SRC.MAXTIME = T.DATETIMESTAMP AND SRC.TKID = T.TKID
WHERE T.STATUS = 'Start'
```
Depending on the actual data, you might want to get MAX(ID)... | How to get matching data using rownumber in SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have a query which I want to return the highest id value in `idevent` that is within a given range of sensor ID's (`sensorID`) however the query is not returning the highest value.
The results when I run the query minus the `max()` statment:
```
mysql> SELECT * FROM events WHERE timestamp BETWEEN "2015-03-09 10:45:... | This could be done with `order by limit`, so all you need to add the following at the end of the given first query
```
order by idevent desc limit 1
``` | Use as , use [order by](http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html)
```
SELECT * FROM events WHERE timestamp BETWEEN "2015-03-09 10:45:35" - INTERVAL 4000 SECOND AND "2015-03-09 10:45:35" AND (sensorID = 34035434 OR sensorID = 34035492 OR sensorID = 34035426 OR sensorID = 34035482 OR sensorID = ... | MySQL max() - not returning max() value | [
"",
"mysql",
"sql",
"database",
"max",
""
] |
I have a dataset like this:
```
+---------------+-------+
| SAMPLE_NUMBER | SCORE |
+---------------+-------+
| 1 | 100 |
| 2 | 97 |
| 3 | 124 |
| 4 | 762 |
| 5 | 999 |
| 6 | 1200 |
| 7 | NULL |
| 8 | NULL |
|... | My guess is that this should be part of your presentation layer since you will have to cast sample\_number to a string (assuming it is a numeric type. An alternative to your requirements is to return the min and max consecutive sample\_number:
```
with t (SAMPLE_NUMBER, SCORE) as (
values (1, 100)
, (2,... | Yes. For your sample data:
```
select (case when score is null then min(sample_number) || '-' || max(sample_number)
else min(sample_number)
end) as sample_number,
score
from table t
group by score
order by min(id)
```
In other words, `group by score` and then fiddle with the sample number.... | Summarise null rows in Oracle | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I'm running what I think is a fairly simple query, and I'm having getting absolutely atrocious return times on the query. When running the query, a sub query as a filter in an `IN` predicate is performing an Index scan and an Index Spool when used as part of the query, but runs an Index Seek when used outside of the `I... | I upvoted all of you who gave me a hand, but this ended up being the solution:
```
SELECT DISTINCT
C.County
, S.State
, C.County_ID
FROM
Leads L
INNER JOIN Contacts ON L.Contact_ID = Contacts.ID AND Contacts.Deleted = 0
INNER JOIN Inventory I ON L.Deleted = 0 AND L.Inv_ID = I.Inv_ID
INNER ... | Try this one:
```
SELECT DISTINCT
C.County
, S.State
, C.County_ID
FROM
Leads L
INNER JOIN Inventory I ON L.Deleted = 0 AND L.Inv_ID = I.Inv_ID (AND L.Acct_ID = 204940
OR L.Acct_ID IN (
SELECT Accounts.Acct_ID FROM Accounts (NOLOCK) WHERE Accounts.Pa... | Table Scan and Eager Spools on IN Predicate | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
we have this table and some data


in some scenario we need to get the **Entities** that they have a property that have special **Value** and the property itself is not important.
the prob is we want to get entitie... | Here are two other ways, in addition to what the other answers already mention:
```
select entity_id from table where value = 1
intersect
select entity_id from table where value = 2
select t1.entity_id from table t1
join table t2 on t1.entity_id = t2.entity_id
where t1.value = 1 and t2.value = 2
``` | Here is one method:
```
SELECT Entity_Id
FROM table
WHERE Value in (1, 2)
GROUP BY Entity_Id
HAVING COUNT(DISTINCT value) = 2;
``` | querying on kinda EVA like model | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Table Author:
```
id | name_author
---------
1 | david
2 | kate
3 | tom
4 | mark
```
Table books:
```
id | name_book
------------
1 | book1
2 | book2
3 | book3
```
table relationships authors and books
```
id_book | id_author
-------------------
1 | 2
1 | 3
1 | 4
2 | 2
1 | 1
3 | 4
```
As a result, I has to get th... | ```
SELECT
b.name_book, GROUP_CONCAT(a.name_author) authors
FROM relationships r
JOIN books b ON r.id_book = b.id
JOIN author a ON r.id_author = a.id
GROUP BY r.id_book
HAVING COUNT(r.id_book) = 4
;
``` | you could write something like that (not tested)
```
select name_book
from books as b
, link_book_author as l
where b.id = l.id_book
group by name_book
having count(id_author) = 4
``` | As select from table only those books which have exactly 4 of the author? | [
"",
"mysql",
"sql",
""
] |
I have a result table like this (after a query has been run):
```
id | time | region
12x-4nm-334 | 16:00 | Utah
12x-4nm-334 | 17:00 | California
12x-4nm-334 | 19:00 | Missouri
12x-4nm-334 | 22:00 | California
983-n2n-aq2 | 8:00 | New York
983-n2n-aq2 | 9:00 | New York
```
There are a few other colu... | Try this:
```
SELECT id, count(DISTINCT region) as RegionCount
FROM table
GROUP BY
id
HAVING count(DISTINCT region) > 1
```
If your DBMS doesn't support `count(distinct )` then this should do instead:
```
SELECT id, count(DISTINCT region) as RegionCount
FROM (
SELECT id, region FROM table GROUP BY id, region... | If you use MySql
```
DELETE FROM table
WHERE id IN ( SELECT x.id
FROM ( select *
FROM table t
GROUP BY id
HAVING COUNT(DISTINCT region) = 1
) as x
)
```
I ... | SQL remove certain duplicate values | [
"",
"sql",
"vertica",
""
] |
I'm trying to compare the columns of a table and fetch the unmatched rows.Can someone help me to write a query to fetch the rows where Email\_ID not in the format of Firstname.Lastname@abc.com in the below scenario.
TABLE
```
S.no Firstname Lastname Email_ID
701 Sean Paul Sean.Paul@abc.com
7... | ```
SELECT *
FROM YourTable
WHERE CHARINDEX(FirstName + '.' + LastName + '@', Email) = 0
``` | You mean something like:
```
select -- some columns
from table
where Email_ID <> (FirstName + '.' + Lastname + '@abc.com')
```
?
There is nothing in SQL to prevent comparing one column with another, and – with a little more syntax – even across rows. | Compare columns of same table in sql server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Interactive exercise 9 [Difficult Questions That Utilize Techniques Not Covered In Prior Sections](https://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial#Difficult_Questions_That_Utilize_Techniques_Not_Covered_In_Prior_Sections) at `https://sqlzoo.net`:
> Find the continents where all countries have a population <= 250... | ```
SELECT name, continent, population
FROM world w
WHERE NOT EXISTS ( -- there are no countries
SELECT *
FROM world nx
WHERE nx.continent = w.continent -- on the same continent
AND nx.population > 25000000 -- with more than 25M population
);
``` | ```
SELECT name, continent, population FROM world x
WHERE 25000000>=ALL (
SELECT population FROM world y
WHERE x.continent=y.continent
AND population>0)
``` | SQL combined SELECT statement | [
"",
"sql",
"subquery",
""
] |
How do I check if a particular id is greater than a(any of) set of values directly..
I thought this would work...but it isn't.. Let table be some table with a column id
```
select id from table where id > any (2,3,4)
```
I get the following error
> You have an error in your SQL syntax; check the manual that corresp... | Try this:
```
SELECT id FROM table WHERE id > GREATEST(2,3,4)
```
UPD: Of course, LEAST, not GREATEST, sorry (thanks @brad). | ```
select id from table where id > 2
```
You can just filter out the minimum value in your group and test against that. | How to check if id greater than a set of values in sql | [
"",
"sql",
""
] |
Let's suppose I have a table T1 with people IDs and other stuff IDs, as the following
```
Table: T1
personID | stuffID
1 | 1
1 | 2
1 | 3
1 | 4
2 | 1
2 | 4
3 | 1
3 | 2
```
And another table T2 with just one column of stuffIDs
```
Table: ... | If I understand correctly, you want to retrieve all the personID's from T1 that have all associated stuffID's found in T2.
You can break this up as follows:
First of all, find all the T1 entries that match with a nested query
```
SELECT personID
FROM T1 WHERE stuffID IN (SELECT stuffID FROM t2)
```
Now you need to ... | ```
select personID
from T1
where stuffID in (select stuffID from t2)
group by personID
having count(distinct stuffID) = (select count(*) from t2)
```
I.e pick a person's stuffids which are in T2, count them (distinct only), and verify same number as in t2. | check if a column contains ALL the values of another column - Mysql | [
"",
"mysql",
"sql",
"relational-division",
""
] |
I have two tables `products` and `product_edits` which hold product information on the pricelist. My app works in a way that if user changes any product info in `products` table it inserts it into `product_edits` table...
PRODUCTS table
```
pk|code|name |description|price|....
-----------------------------------
... | It's better to use `EXISTS` instead of `IN`, in this case.
You want the search to stop once you found a match, not go over all of the results from `product_edits`.
So do it like this:
```
SELECT
code, name, description
FROM products p
WHERE NOT EXISTS (SELECT 1 FROM product_edits e WHERE e.code = p.code)
UNION
SE... | ```
select code, name, description from products
where code not in(select code from product_edits)
union
select code, name, description from product_edits
``` | MYSQL: UNION results between two tables where omitting records from first table if PK found in second table | [
"",
"mysql",
"sql",
"union",
""
] |
I have an Oracle DB table `tab` with two key fields: `f1` and `f2`. Now I need to select all those entries from that table, where `f1` is the same for at least two entries (so only `f2` differs).
```
f1 |f2
----+----
a |123
b |123
c |123
d |123
b |456
e |123
c |789
```
So in the example above, the SELE... | You can use `count` in analytic version:
```
select f1, f2
from (
select tab.*, count(1) over (partition by f1) cnt from tab
)
where cnt>1
```
Results:
```
F1 F2
----- ----------
b 123
b 456
c 123
c 789
``` | This should work and look familiar to you:
```
SELECT f1, f2
FROM tab t1
WHERE f1 IN (SELECT f1
FROM tab t2
WHERE t1.f2 <> t2.f2)
```
Basically we check to see if `f1` is found again in itself where the `f2` does not match. | Select DB records where some key values are the same | [
"",
"sql",
"oracle",
""
] |
When I run in SQL Developer this code,
```
SELECT EMPLOYEE_ID AS NON_MANAGER_EMPLOYEES
FROM EMPLOYEES
MINUS
SELECT MANAGER_ID
FROM EMPLOYEES;
```
Shows:
```
NON_MANAGER_EMPLOYEES
104
107
141
142
143
144
174
176
178
200
202
206
```
Which is what I want. Now I just want to add a column to that so it shows their las... | One option would be to `join` the results back to the employee table and use a subquery:
```
SELECT E.EMPLOYEE_ID, E.LAST_NAME
FROM EMPLOYEES E
JOIN (
SELECT EMPLOYEE_ID
FROM EMPLOYEES
MINUS
SELECT MANAGER_ID
FROM EMPLOYEES
) E2 ON E.EMPLOYEE_ID = E2.EMPLOYEE_ID
```
--... | Minus is really the wrong operation here. I would leverage `EXISTS` instead. For example,
```
SELECT employee_id AS non_manager_employees, last_name
FROM employees e
WHERE NOT EXISTS
(SELECT NULL FROM employees m WHERE e.employee_id = m.manager_id)
```
This will filter out any rows where the given employee is als... | Add a column to a query result in SQL Developer | [
"",
"sql",
"oracle",
""
] |
I get this table :

I use this where :
```
where FoodID=1
```
when i Change My where with this :
```
where FoodID=1 and DayId=1 or DayId is null
```
Filed dayid value change to null for All rows .
` arround the or operator:
```
where FoodID=1 and (DayId=1 or DayId is null)
```
if not first the `and` operator is evaluated and then `or` | ```
where FoodID=1 and (DayId=1 or DayId is null)
``` | set Null to value when use Is null in where | [
"",
"sql",
"select",
""
] |
```
a.geosid a.Latitude a.Longitude b.Latitude b.Longitude b.geosid
9589565 -36.013472 -71.426018 -36.0135 -71.426 9589565
9586071 -36.015 -71.498 -36.1104 -71.4416 9586071
9589565 -36.013473 -71.426017 -36.0135 -71.426 9589565
```
The da... | Sounds fairly straightforward, since they're both numbers. Since you're using an inner join, you can either put the criteria in the join:
```
SELECT *
FROM [ChileCSVimports].[dbo].[tLocation] a
JOIN AIRGeography..tGeography b
ON a.GeographySID = b.GeographySID
AND ABS(a.Latitude - b.Latitude... | You can add to your `JOIN` criteria or use `WHERE` criteria to compare the values:
```
SELECT *
FROM [ChileCSVimports].[dbo].[tLocation] a
JOIN AIRGeography..tGeography b
ON a.GeographySID = b.GeographySID
AND ABS(a.Latitude - b.Latitude) < 0.0002
AND ABS(a.Longitude - b.Longitude) ... | Join statement with condition in sql | [
"",
"sql",
"join",
"conditional-statements",
""
] |
I have a table looking like this:
```
ID USER INVENTORY [...]
1 A X
2 A Y
3 A Z
4 B X
5 B Y
6 C X
7 C Z
```
I would like to select all columns in rows of USERs who have both X and Y in their inventory. Like so:
```
ID USER INVEN... | Here's one way using `exists` with conditional aggregation:
```
select id, user, inventory
from yourtable y
where inventory in ('X','Y') and exists (
select 1
from yourtable y2
where y.user = y2.user
group by user
having sum(inventory = 'X') > 0 and sum(inventory = 'Y') > 0
)
```
* [SQL Fiddle Demo](http:... | The most efficient way is probably to use two `exists` statements:
```
select t.*
from table t
where t.inventory in ('X', 'Y') and
exists (select 1 from table t2 where t2.user = t.user and t2.inventory = 'X') and
exists (select 1 from table t2 where t2.user = t.user and t2.inventory = 'Y');
```
You want a... | Select intersecting users | [
"",
"mysql",
"sql",
"database",
""
] |
I have a stored proc in Oracle, and we're limiting the number of records with ROWNUM based on a parameter. However, we also have a requirement to know whether the search result count exceeded the arbitrary limit (even though we're only passing data up to the limit; searches can return a lot of data, and if the limit is... | You could use a nested subquery:
```
select id, case when max_count > 3 then 'Exceeded' else 'OK' end as flag
from (
select id, rn, max(rn) over () as max_count
from (
select id, rownum as rn
from t
)
where rownum <= 4
)
where rownum <= 3;
```
The inner level is your actual query (which you probably hav... | You can add a column to the query:
```
select * from (
select . . . , count(*) over () as numrows
from . . .
where . . .
) where rownum <= 1000;
```
And then report `numrows` as the size of the final result set. | Find out if query exceeds arbitrary limit using ROWNUM? | [
"",
"sql",
"oracle",
"plsql",
"rownum",
""
] |
I had an issue with a MySQL statement that was returning null all the time, and although I was able to figure it out, the cause left me a bit puzzled.
This is a simplified version of the problematic query:
```
SELECT id FROM users WHERE id = id = 2;
```
The error happened because `id =` is repeated, removing one of ... | # Prerequisites to understand how chained comparisons in MySQL work
## Understanding SELECT-WHERE query
This is pretty obvious, but I'm making this answer for every programmer, even if you don't really know how SQL works. A `SELECT-WHERE` query, basically:
1. Loops every row affected by the query and
2. evaluates th... | I do not know MYSQL at all but suspect that you are encountering a side effect of the fact that each predicate on a where clause must evaluate to true. E.g.
```
Select *
from table
where 1 = 1
```
is in effect saying
```
Select *
from table
where is_true(1 = 1)
```
I suggest you try other values than 1 and 0 and ... | Chained comparisons in MySQL get unexpected result | [
"",
"mysql",
"sql",
"database",
""
] |
Is this the best way to select default value from the table if selecting value is `0` or `null`?
```
DECLARE @value INT = 15
DECLARE @defaultValue INT = 12
SELECT IIF(ISNULL(@value,0) = 0, @defaultValue, @value)
``` | Specify "best". Since `IIF` works only in SQL-Server i'd use `CASE` which is ANSI SQL standard and works in every(?) rdbms:
```
SELECT CASE WHEN ISNULL(@value,0) = 0 THEN @defaultValue ELSE @value END
```
Actually [`IIF`](https://msdn.microsoft.com/en-us/library/hh213574.aspx) is even translated to `CASE`:
> IIF i... | You can use the [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx). It evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to `NULL`. It is used for this purpose to get the first `not null` value.
```
SELECT COALESCE(@value,@defaultVa... | Should i use IIF and ISNULL to select a default-value? | [
"",
"sql",
"sql-server",
""
] |
I would like a union query where the second query is used only if the first does not return any results.
a simple example...
table
```
create table tbl (
name varchar(3),
lang varchar(3)
);
insert into tbl (name, lang) values ('foo', 'en');
insert into tbl (name, lang) values ('foo', 'es');
insert into tbl (n... | Use this:
```
SELECT name, lang
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY name ORDER BY CASE WHEN lang = 'es' THEN 1 ELSE 2 END) AS rn
FROM tbl ) t
WHERE t.rn = 1
```
You can adjust to `CASE` clause within `OVER` to accomodate any other language. | Use `Row_Number()` window function.
```
select name, lang
from
(
SELECT name, lang,row_number(partition by name order by order_column) RN
FROM tbl
) a
where RN=1
```
Keep what ever `column` which helps you to find the `first` value per `Name` `order by` in `row_number` | SQL Server (TSQL) Select first value if exists, otherwise select other | [
"",
"sql",
"sql-server",
""
] |
I have a column named phone\_number and I wanted to query this column to get the the string right of the last occurrence of '.' for all kinds of numbers in one single sql query.
example:
515.123.1277
011.44.1345.629268
I need to get 1277 and 629268 respectively.
I have this so far:
select phone\_number,
case when ... | It should be as easy as this regex:
```
SELECT phone_number, REGEXP_SUBSTR(phone_number, '[^.]*$')
FROM employees;
```
With the end anchor `$` it should get everything that is not a `.` character after the final `.`. If the last character is `.` then it will return `NULL`. | Search for a pattern including the period, `[.]` with digits, `\d`, followed by the end of the string, `$`.
Associate the digits with a character group by placing the pattern, `\d`, in parenthesis (see below). This is referenced with the subexpr parameter, `1` (last parameter).
Here is the solution:
```
SCOTT@dev> l... | substring, after last occurrence of character? | [
"",
"sql",
"oracle",
"substring",
""
] |
So given a table like the one below, I would like to grab rows where `id` has at least three consecutive years.
```
+---------+--------+
| id | year |
+------------------+
| 2 | 2003 |
| 2 | 2004 |
| 1 | 2005 |
| 2 | 2005 |
| 1 | 2007 |
| 1 | 2008 |
+---------+---... | This one works and can be fast when you have at least an index on the id-field:
```
WITH t1 AS (
SELECT *
FROM (VALUES
(2,2003),
(2,2004),
(1,2005),
(2,2005),
(1,2007),
(1,2008)
) v(id, year)
)
SELECT DISTINCT t1.id
FROM ... | You can use `JOIN` approach (*self-join*):
```
SELECT t1.id
FROM tbl t1
JOIN tbl t2 ON t2.year = t1.year + 1
AND t1.id = t2.id
JOIN tbl t3 ON t3.year = t1.year + 2
AND t1.id = t3.id
```
[**SQLFiddle**](http://sqlfiddle.com/#!15/ddf2a8/3) | How do I group a collection of elements by whether or not they have consecutive values? | [
"",
"sql",
"postgresql",
"gaps-and-islands",
""
] |
Let's say I have two columns: **Date** and **Indicator**
**Usually the indicator goes from 0 to 1** (when the data is sorted by date) and **I want to be able to identify if it goes from 1 to 0 instead**. Is there an easy way to do this with SQL?
I am already aggregating other fields in the same table. If I can add th... | This isn't a teradata-specific answer, but this *can* be done in normal SQL.
Assuming that the sequence is already 'complete' and xn+1 can be derived from xn, such as when the dates are sequential and all present:
```
SELECT date -- the 1 on the day following the 0
FROM r curr
JOIN r prev
-- join each day with the pr... | Joining the table against it self it quite generic, but most SQL Dialects now support Analytical Functions. Ideally you could use `LAG()` but TeraData seems to try to support the absolute minimum of these, and so so they point you to use `SUM()` combined with `rows preceding`.
In any regard, this method avoids a poten... | SQL query to identify 0 AFTER a 1 | [
"",
"sql",
"teradata",
""
] |
I need to drop all User-Defined Types, User-Defined Data Types and User-Defined Tables (all in Types folder). Is it possible to do this using a T-SQL script, or must I use SSMS? | ```
select 'drop type ' + quotename(schema_name(schema_id)) + '.' + quotename(name)
from sys.types
where is_user_defined = 1
```
You can try getting all you user defined type objects and create a script using this query or Generate Script Clicking Task under your database.
<http://blog.falafel.com/t-sql-drop-all-obj... | For the above link posted
[T-SQL: Drop All Objects in a SQL Server Database](http://blog.falafel.com/t-sql-drop-all-objects-in-a-sql-server-database/)
I added following code to replace check Constraint from [Drop Constraint by Stefan Steiger](https://stackoverflow.com/questions/12721823/how-to-drop-all-foreign-key-con... | Drop All User-Defined Types from SQL Server | [
"",
"sql",
"sql-server-2008",
""
] |
I'm trying to implement a trigger on a SQL Server database, which will insert a new row in `table2` whenever a row is updated in `table1`. I want to get the row data (`table1`) before update.
For example, I have the following rows:
```
table1: table2:
________________________ ______... | You need to use the `Deleted` pseudo table in your trigger, which contains the **old** values (before the `UPDATE`):
```
CREATE TRIGGER triggername
ON table1
FOR UPDATE
AS
Begin
INSERT INTO table2(name)
SELECT d.name
FROM Deleted d
End
```
The `Inserted` pseudo table contains the **new** values - after ... | This will only return the new value:
```
INSERT INTO table2(name)
SELECT i.name
FROM Inserted i
```
This however will return the value before the update
```
INSERT INTO table2(name)
select d.name
from inserted i
join deleted d
on (i.id = d.id)
``` | Create a trigger that inserts old values into other table when a row is updated | [
"",
"sql",
"sql-server",
"triggers",
""
] |
Is there any way to load results from a query that takes more than a minute to return results?
Let me elaborate on the situation. I have a SQL query which is very convoluted. it has multiple join on different on 5 different tables because of the level of normalization involved.
So my query return around 6k records, h... | While you've not specified what DBMS or web platform you're using, in general this will not be possible if you are using an ORDER BY in your query, as this will require the whole resultset in order to work.
It sounds like you should instead focus on optimising your query, or getting the results cached so that you don'... | I don't know your system, but I will try give you some advices.
You can load the page without records, if possible, and load them with ajax and insert rows dynamically.
Other possibility is to do this query as the first step at your backend, but asynchronous, and get result at last step. It will reduce this time, pro... | How to pass results from slow sql query in runtime | [
"",
"sql",
"dynamic",
""
] |
Is there any easy way to select every record for two tables, kind of hard to explain but if I have two tables Client and Product
```
Client
A
B
C
Product
1
2
3
```
What query would get a result like this:
```
RESULT
A1
A2
A3
B1
B2
B3
C1
C2
C3
``` | That's called a `cross join` (or a cartesian product):
```
select c.field, p.field
from client c
cross join product p
```
It's fairly straight-forward to combine the columns together at this point. | Use `CROSS JOIN`
```
SELECT C.client_column
+ CONVERT(VARCHAR(50), P.Product_column)
FROM client C
CROSS JOIN product P
``` | Select every record in SQL | [
"",
"sql",
"sql-server",
"database",
"resultset",
""
] |
I have a table which has a column `CreatedDate` that is of type `varchar(100)`. The rows for that columns are:
```
CreatedDate
--------------
March 6, 2015
March 6, 2015
March 6, 2015
March 6, 2015
March 6, 2015
March 6, 2015
March 7, 2015
March 10, 2015
```
If I do the following query, the date aren't ordering corre... | Assuming it can all be safely converted to date or datetime:
```
CAST(CD AS DATE)
```
If not you'd have to split the string up and make it a date manually. | Change the `ORDER BY` clause to:
```
ORDER BY TRY_PARSE(CreatedDate AS DATE) ASC;
```
If the `CreatedDate` column contains values that aren't valid dates, [TRY\_PARSE](https://msdn.microsoft.com/en-us/library/hh213126.aspx) returns NULL for sort evaluation instead of throwing an error message.
If you have control ov... | How to convert varchar to date for ordering in SQL Server | [
"",
"sql",
"sql-server-2012",
""
] |
I have a simple table:
```
column 1 column2 column3
AA AAAA TT
AA BB EE
AB C AABBCC
ABC XXX XYZ
AABB ... | You could just use OR key-word as this:
```
SELECT column1, column2, column3
FROM sample
WHERE column1 like 'AA%'
OR column2 like 'AA%'
OR column3 like 'AA%'
``` | You union query is also correct bt in case of simplicity i agree with Or query | PostgreSQL: finding multiple columns that match a like clause | [
"",
"sql",
"postgresql",
"sql-like",
""
] |
So I'm trying to get a part of a value from a column and insert that part into another column - new column. BOTH columns are in the same table. So what i want should look something like this:
```
id newColumn oldColumn
1 12 123 some text
2 24 246 some text
....
```
I know... | First you have to add new col using following command:-
```
ALTER TABLE TAB_NAME
ADD COLUMN COL_NAME(VARCHAR(10));
```
After that execute this command:-
```
UPDAET TAB_NAME
SET COL_NAME = SUBSTRING(OLDCOLUMN, 1, 2);
```
I think this might help you. | No need to join, it's just a plain `UPDATE`:
```
update tablename set newColumn = substring(oldColumn from 1 for 2)
```
`substring` is ANSI SQL, some dbms have substr and other versions.
The question is why you are doing this? What do you expect to find in newColumn if someone later updates oldColumn to another valu... | How to store part of a field value in another column in SQL | [
"",
"sql",
"substr",
"self-join",
""
] |
i have the SQL code to generate the date list between two dates, but i want to generate the week days (Business days) from the given two dates,
```
DECLARE @MinDate DATE = '20140101', @MaxDate DATE = '20140106';
SELECT TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.obj... | Try this:
```
DECLARE @MinDate DATE = '20140101',
@MaxDate DATE = '20140106'
;WITH N1 (N) AS (SELECT 1 FROM (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) n (N)),
N2 (N) AS (SELECT 1 FROM N1 AS N1 CROSS JOIN N1 AS N2),
N3 (N) AS (SELECT 1 FROM N2 AS N1 CROSS JOIN N2 AS N2),
N4 (N) AS (SELECT ROW_NU... | Make the original query as `sub-select` which generates all the dates between two given dates then do the filteration in `outer query`.
```
SET DATEFIRST 1
select [Date] from
(
SELECT TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1,@MinDate)
FROM sys... | List all working dates between two dates in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012-express",
""
] |
I have a row of the database like this:
```
1|abc|10|30|12
```
The biggest value is 30 and the second highest is 12. How can I get the second value for each row in my table? | This will work with any number of columns, just make sure you add them to the concatenated list where labelled `merge_col` in my query below:
```
select col1, col2, col3, col4, col5, second_highest
from (select x.*,
regexp_substr(merge_col, '[^|]+', 1, levels.column_value) as second_highest,
... | There are different ways to achieve that. try this one for instance:
```
SELECT MAX('column_name') FROM 'table_name'
WHERE 'column_name' NOT IN (SELECT MAX('column_name') FROM 'table_name' )
```
You basically exclude the highest number from your query and then you select the highest out of the rest . | How to find the 2nd highest value in a row with Oracle SQL? | [
"",
"sql",
"oracle",
""
] |
Example
if two products
```
id name
1 product A
2 product B
```
And for each products I've attributes
```
id product_id value
1 1 1
2 1 2
3 2 3
3 2 4
```
And I need to select products by value of attributes.
I need products which have attributes with 1 AND 2 values.
... | Do a group by to find product id's with both 1 and 2 attributes. Select from products where product id found by that group by:
```
SELECT *
FROM product_table
WHERE id IN (select product_id
from attribute_table
where value in (1,2)
group by product_id
having count(di... | To rephrase your question, you really need those products, which has both `1` and `2` *within* the values of their attributes:
```
SELECT product.*
-- , array_agg(attribute.value) attribute_values
-- uncomment the line above, if needed
FROM product
LEFT JOIN attribute ON product.id = attribute.produc... | SELECT one entry with two left joins. SQL | [
"",
"sql",
"postgresql",
""
] |
I am creating a testing system where users are allowed to re-test until they have passed. I would like to get a list, for a given UserID, of tests which are assigned to them which they have scored less than passing (100% for this example) on.
I have the following tables:
> (Everything here has been adapted for simpli... | I think I understand what you are after now, give this a go:
```
SELECT DISTINCT
TestID,
TestName
FROM
`Users` AS u
RIGHT JOIN
`Users_have_Tests` AS ut
ON
u.UserID = ut.UserID
LEFT JOIN
`Tests` AS t
ON
ut.TestID = t.TestID
... | Have you tried the following?
Edit I noticed you want to see the highest score, so I created a subquery
Edit I forgot a grouping.
Also, Test needs to be joined on both the TestID and UserID.
```
SELECT
TestID,
TestName,
HighestScore
FROM
`Users` AS u
... | Retrieving only rows for which a join has a dependancy | [
"",
"mysql",
"sql",
"subquery",
""
] |
I am trying to obtain all posts created by all users a given user follows.
Tables: posts, users, followers
## Users
```
id int(255)
```
Which is associated with:
## Followers
```
id int(255)
user_id int(255) //The id of person that's is following
following int(255) //The id of person being followed
```
Which is ... | A simple join should suffice. The `?` is where the user id of the 'follower' goes.
```
SELECT * FROM Posts p
INNER JOIN Followers f ON (f.following = p.user_id)
WHERE f.user_id = ?;
``` | To do this queries you just have to join multiple tables
```
SELECT P.*
FROM users U
INNER JOIN followers F ON (F.user_id = U.id)
INNER JOIN users FU ON (FU.id = F.following)
INNER JOIN posts P ON(P.user_id = F.id)
WHERE U.id = :id
``` | Select all posts created by all users a given user follows | [
"",
"mysql",
"sql",
""
] |
I'm trying to get a count on how many times BNxxxx has been commented in the comments cell. So far, I can make each cell be counted once, but there may be multiple comments in a cell containing BNxxxx.
For example, this:
```
-------
BN0012
-------
BN0012
-------
BN0012
BN0123
-------
```
should show an output of ... | I'm going to assume that your `COMMENTS` table has a primary key column (such as `comment_id`) or at least that `comments` isn't a `CLOB`. If it is a `CLOB` then you're not going to be able to use `GROUP BY` on that column.
You can accomplish this as follows without even a lookup table of `BN....` values. No guarantee... | You have a problem. Let me assume that you have a table of all known BN values that you care about. Then you can do something like:
```
select bn.fullbn, count(*)
from tableBN bn join
comments c
on c.comment like ('%' || bn.fullbn || '%')
group by bn.fullbn;
```
The performance of this might be quite slow.
... | SQL using Count, with same "Like" multiple times in same cell | [
"",
"sql",
"oracle",
"count",
"cell",
"sql-like",
""
] |
I am trying to run this query on pervasive database
```
select cust_no,cust_name,sum(bvtotal) as Amount
from sales_history_header
where cust_no is not null and number is not null and bvtotal > 1000 and in_date < 20140101
group by cust_no,cust_name
order by sum(bvtotal) desc;
```
How do I exclude those group results... | You need to exclude all records based on a set of ids. Typically, you do this with a subquery:
```
SELECT cust_no,
cust_name,
sum(bvtotal) AS Amount
FROM sales_history_header
WHERE cust_no IS NOT NULL
AND number IS NOT NULL
AND bvtotal > 1000
AND cust_no NOT IN (
SELECT cust_no
FRO... | I think you need to specify you date constant as a date unless you really want to be dealing with integers.
```
select cust_no,cust_name,sum(bvtotal) as Amount
from sales_history_header
where cust_no is not null and number is not null and bvtotal > 1000 and in_date < '2014-01-01'
group by cust_no,cust_name
order by ... | pervasive query with group by issue | [
"",
"mysql",
"sql",
"pervasive-sql",
""
] |
I have field REPORTDATE (DATETIME).
In SQL Developer i can see its value in this format
`29.10.2013 17:08:08`
I found that in order to do the select of just a DATE I need to execute this:
```
SELECT TO_DATE (REPORTDATE, 'DD.MON.YYYY') AS my_date
FROM TABLE1
```
but it returns `0RA-01843: not a valid month`
I want ... | > TO\_DATE (REPORTDATE, 'DD.MON.YYYY')
This makes no sense. You are converting a date into a date again. You use **TO\_DATE** to convert a string literal into **DATE**.
> I want result to return only 29.10.2013
You could use **TRUNC** to truncate the time element. If you want to use this value for DATE calculations,... | Use this:
```
SELECT trunc(REPORTDATE, 'DD') AS my_date
FROM TABLE1
```
This will not change the type of the returning object, only truncates everything below "day" level.
If you are ok with returning a String, then you can just do:
```
SELECT TO_CHAR(REPORTDATE, 'DD.MM.YYYY') AS my_date
FROM TABLE1
``` | Oracle SQL "SELECT DATE from DATETIME field " | [
"",
"sql",
"oracle",
"date",
"select",
""
] |
I have a table named `Click` in sql database. This table stores clicks of everything. This table has a field named `EntityTypeId` that says this row is for which entity. I want to fetch a special type of clicks and store them in another table. So I should select them from `Click` table and insert them in `PriceClick` t... | Use `INSERT INTO`:
```
INSERT INTO PriceClick(ClickId, EntityTypeId)
SELECT ClickId, EntityTypeId
FROM Click
WHERE EntityTypeId = 2
``` | Use `SELECT INTO` if you don't have the DestinationTable or Use `INSERT INTO` as the other answer mentioned (@wewesthemenace) if you already created your DestinationTable
```
SELECT *
INTO DestinationTable
FROM SourceTable
WHERE ....
``` | How to fetch a list of rows and foreach in it in sql? | [
"",
"sql",
"sql-server",
"sqlcommand",
""
] |
Gives me error when I try to insert and it finally inserts after couple of retries with out any error.
```
SQL Error: ORA-00001: unique constraint (ALERTS2.PK_UP_MODULE_MASTER) violated.
*Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.
```
**INSERT statement:**
```
INSERT INTO up_module_ma... | Looks like `MR_ID` is not an identity seed. If another process is attempting to insert a record at the same time as you, both will try to insert the same ID and you will get this error. I suggest that you change the column to be auto incrementing. You will need to create a sequence and then a trigger if using pre versi... | the problem is, that someone other inserted and commited a row with the same key meanwhile
consider using a sequence (it looks like the sequence is already defined):
*SELECT seq\_name.nextval, ... FROM dual* | How do I fix SQL Error: ORA-00001: unique constraint (ALERTS2.PK_UP_MODULE_MASTER) violated | [
"",
"sql",
"oracle",
""
] |
I have a function that needs to perform a long update on multiple large tables. During the update 2-3 tables at a time need to be locked in EXCLUSIVE mode.
Since not all the tables need to be locked at the same time, ideally I'd want to LOCK only those tables I'm updating at the time, and then remove the lock once I'm... | In **Postgres 11** or later, consider a **`PROCEDURE`** which allows transaction control. See:
* [Do stored procedures run in database transaction in Postgres?](https://stackoverflow.com/questions/28250376/do-stored-procedures-run-in-database-transaction-in-postgres/28251922#28251922)
---
With **functions**, there i... | In pg11 you now have `PROCEDURE`s which let you release locks via `COMMIT`. I just converted a bunch of parallel executed functions running `ALTER TABLE ... ADD FOREIGN KEY ...` with lots of deadlock problems and it worked nicely.
<https://www.postgresql.org/docs/current/sql-createprocedure.html> | PostgreSQL obtain and release LOCK inside stored function | [
"",
"sql",
"postgresql",
"plpgsql",
""
] |
I have this:
```
SELECT ROW_NUMBER() OVER (ORDER BY vwmain.ch) as RowNumber,
vwmain.vehicleref,vwmain.capid,
vwmain.manufacturer,vwmain.model,vwmain.derivative,
vwmain.isspecial,
vwmain.created,vwmain.updated,vwmain.stocklevel,
vwmain.[type],
vwmain.ch,vwmain.co2,vwmain.mpg,vwmain.term,vwmain.m... | You can't reference the field like that. You can however use a subquery or a common-table-expression:
Here's a subquery:
```
SELECT *
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY vwmain.ch) as RowNumber,
vwmain.vehicleref,vwmain.capid,
vwmain.manufacturer,vwmain.model,vwmain.derivative,
vwmai... | Using top:
```
SELECT top 1 vwmain.vehicleref,vwmain.capid,
vwmain.manufacturer,vwmain.model,vwmain.derivative,
vwmain.isspecial,
vwmain.created,vwmain.updated,vwmain.stocklevel,
vwmain.[type],
vwmain.ch,vwmain.co2,vwmain.mpg,vwmain.term,vwmain.milespa,
homepagefeature... | SQL ROW_NUMBER OVER syntax | [
"",
"sql",
"sql-server",
"window-functions",
""
] |
The answers for [this question](https://stackoverflow.com/questions/149784/how-do-you-copy-a-record-in-a-sql-table-but-swap-out-the-unique-id-of-the-new-ro) almost answer mine, but not quite. How do I turn this:
```
col0 col1 col2
data0 a foo
data1 b foo
data2 c fee
data3 d fee
```
into this? (duplicatin... | ```
insert into T (col0, col1, col2)
select col0, col1, 'bar'
from T
```
If by "copy" you mean a `select` then a union would work as in other answers or you could try this:
```
select col0, col1, case when num = 0 then col2 else 'bar' end as col2
from T, (select 0 as num union all select 1) as dup
``` | One option, `union all`:
```
select col0, col1, col2
from yourtable
union all
select col0, col1, 'bar'
from yourtable
``` | How do you copy a row in a SQL table and alter one of the column values? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a simple (I suppose) problem, which is baffling me (I'm not a SQL expert as you will see soon... :-).
I have a table `person` with fields `id` and `name`, and a table `comment` with field `id`, `id_person` and `text`:
```
---------------
table: person
---------------
id | name
---------------
--------------... | I'm not sure I see what's wrong with what you've tried. You hardcode the ID, but if you just swap that out, it should be fine.
```
SELECT *
FROM person
WHERE (SELECT COUNT(*)
FROM comment
WHERE id_person = person.id) >= N
```
Another solution, whether better or not is hard to know (you should try each i... | Simplest would be to use a `group by` and a `having` clause like this
```
select p.name
from person p
inner join comment c on c.id_person = p.id
group by
p.name
having count(*) = 2
```
As a sidenote: I would rename your columns to
```
---------------------------
table: person
---------------
id_per... | SQL: How to select persons with at least N comments? | [
"",
"sql",
"sqlite",
""
] |
I have a mysql query:
```
SELECT zip AS z FROM zip WHERE zip = 90210;
```
When the row matching 90210 is found, it returns:
```
+-------+
| z |
+-------+
| 90210 |
+-------+
```
When the row is not found, an empty set is returned.
```
Empty set (0.01 sec)
```
What I am trying to figure out is how in the case ... | To guarantee that a query returns one row, you can use aggregation. Here is one method:
```
SELECT COALESCE(MAX(zip), 'false') AS z
FROM zip
WHERE zip = '90210';
```
This assumes that `zip` is a string, so the types are compatible. If not, you might want to convert it to a string because you are clearly expected a st... | This query will do what you want. Selecting from `Dual` means selecting from no table. The idea is to select all the zip codes, and union it with "false" string (you can replace it with whatever you want) if there's no entry for that zip code.
```
SELECT zip AS z FROM zip WHERE zip = 90210
UNION ALL
SELECT "false"... | How to replace 'Empty set' in a mysql query? | [
"",
"mysql",
"sql",
""
] |
I have a similar table to this dummy data, where there are 3 records for one individual. I would like to change that to one record with multiple columns. What is complicating it for me the most is I want the 3 most current Products based off of Date\_Purchased
Existing:
```
NameFirst NameLast MbrKey ... | Try `PIVOT`:
```
DECLARE @t TABLE
(
Name NVARCHAR(MAX) ,
Product NVARCHAR(MAX) ,
Date DATE
)
INSERT INTO @t
VALUES ( 'John', 'ProductA', '20150101' ),
( 'John', 'ProductA', '20150102' ),
( 'John', 'ProductB', '20150103' ),
( 'John', 'ProductB', '20150112' ),
... | Use the `max()` aggregate function with the case statements and a `group by` clause. You can also skip a level of subqueries:
```
select
MbrKey, NameLast, NameFirst,
max(Case when rn = 1 then Product else null end) as Product1,
max(case when rn = 2 then Product else null end) as Product2,
max(case when rn = ... | SQL Multiple rows/records into one row with 3 columns | [
"",
"sql",
"sql-server-2008",
"t-sql",
"pivot",
""
] |
I have two tables:
```
create table creations (id int)
create table images (creation_id int, path varchar)
```
In the `images.path`, there is a limited number of possible values, like 'my documents', 'desktop', etc (it's a datamining DB).
I want to find the number of different paths for a creation, and how many of t... | I'm not certain I understand the question, nor why you have supplied an query as an answer.
However all I would suggest is moving the correlated query into an APPLY. Below I have used OUTER APPLY which would allow all creation records even if not found in paths. A CROSS APPLY would limit results to only creations foun... | It works if I first count the number of `path`s for each creation, then group on this, by using the results as a table:
```
select nb_path, COUNT(*) as nb_creations
from (
select c.id,
(
select count(distinct [path])
from images as i
where i.creation_id = c.id
) as nb_path
from ... | Double count on two tables | [
"",
"sql",
"sql-server",
""
] |
I am having a difficult time explaining this in words.
What I am trying to do:
I have the following table
```
employerID, userID
45 1
48 1
53 1
45 2
55 2
```
I want to build a query to return the rows
```
employerID, userID
45 1
48 1
53 1
45 ... | So you want to find all rows where either the `userID = 1` or where at least one record exist with the same `employerID` and `userID = 1`?
Then you can use this sql which does exactly that:
```
SELECT employerID, userID
FROM dbo.TableName t
WHERE t.userID = 1 -- either userID = 1
OR -- or userID = 2... | One more version:
```
DECLARE @t TABLE ( EmpID INT, UserID INT )
INSERT INTO @t
VALUES ( 45, 1 ),
( 48, 1 ),
( 53, 1 ),
( 45, 2 ),
( 55, 2 )
SELECT * FROM @t
WHERE EmpID NOT IN ( SELECT EmpID FROM @t WHERE UserID = 2
EXCEPT
SELECT... | Find all of the rows in that are in a subgroup of a table | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
I have MySQL table have `2 columns (col1,col2)` I want to make query to get the count of cells where `value = 4`
I use `Select COUNT(*) from tbl where col1=4 OR col2=4`
But it give me 1 as they are in same row it should be 2 because (4) found 2 times
```
col1 col2
------------- -----------
5 ... | you can add the result of two select statements. try this one
```
SELECT
(SELECT COUNT(*) FROM tbl WHERE col1 = 4 )+
(SELECT COUNT(*) from tbl WHERE col2 = 4)
AS SumCount
```
> result would be: 2 | I think this will count the cells properly. Including counting both col1 and col2 being 4 in the same row.
```
SELECT COUNT(IF(col1=4,N,NULL)) + COUNT(IF(col2=4,N,NULL)) cellcnt FROM tbl
``` | Counting all occurances of a certain value in both of two columns | [
"",
"mysql",
"sql",
""
] |
I have dynamic query which might programatically generate more than a thousand where clauses, each of them could be like (column a = '1' and b = '2' ) with little variations. May I know whether so many conditions in one Sql query will have performance issue? column a is a varchar max , no index created. the table it qu... | Yes. A thousand `where` clauses can impact performance. If you could, I would recommend creating a temporary table with the values and using a `join` for the logic. You should create an index on the temporary table.
Note: you could use a trick on the main table, by adding a computed column that concatenates the column... | This will be inefficient, but there are also limits on query size and number of parameters that could cause errors in your application if you build queries this way. These limits are not always clear, depending on a number of factors, so it could lead to subtle errors that are hard eliminate.
See [this question](https... | Will many where clauses impact query performance | [
"",
"sql",
"sql-server",
"performance",
"query-optimization",
""
] |
I want to perform following oracle SQL query
```
SELECT t1.Technology, count(t1.trax_id) as "Current number of items", to_char(to_date(max(round((SYSDATE - t1.time_event) * 24 * 60 * 60)),'sssss'),'hh24:mi:ss') as "max_ages"
from dm_procmon t1
group by t1.Technology;
```
The problem is the date substration formula.
... | you try to convert to\_date(%number of seconds%, 'sssss'), that is the problem. just use `TO_CHAR(MAX(TO_DATE('20000101','yyyymmdd')+(SYSDATE - t1.time_event)),'hh24:mi:ss')`; this will function correctly for intervals < 1day | The following will give a `DAY TO SECOND INTERVAL` for all dates within about 68 years of one another:
```
SELECT t1.technology, COUNT(t1.trax_id) AS "Current number of items"
, NUMTODSINTERVAL(ROUND((SYSDATE - MIN(t1.time_event) * 24 * 60 * 60), 'SECOND') AS "max_ages"
FROM dm_procmon t1
GROUP BY t1.technolog... | Oracle sql: ORA-01830 when date calculation happens | [
"",
"sql",
"oracle",
"compiler-errors",
""
] |
I discover some behavior I didn't know before. Why this line of code does not work?
```
SELECT REPLACE('','','0') ==> returns ''
```
I can't even have `''` in where condition. It just doesn't work. I have this from imported Excel where in some cells are no values but I'm not able to remove them unless I used `LEN('')... | There is nothing to replace in an empty string. [`REPLACE`](https://msdn.microsoft.com/en-us/library/ms186862.aspx) replaces a **sequence** of characters in a string with another set of characters.
You could use `NULLIF` to treat it as `NULL` + `COALESCE` (or `ISNULL`):
```
declare @value varchar(10);
set @value = ''... | You can use CASE for this.
```
(CASE WHEN *YOURTHING* = '' THEN '0' ELSE *YOURTHING* END)
AS *YOURTHING*
``` | REPLACE empty string | [
"",
"sql",
"sql-server-2008-r2",
""
] |
Below query I am trying to filter status id =7 records for team\_id>1
But want to include records with status\_id=7 for team\_id=1.How can we write the query.
```
SELECT MAX(created_date) AS maxtime,
TEAM_ID,
ticket_id
FROM ri_ticket_status_history
WHERE status_id<>7
GROUP BY TEAM_ID,ticket_... | A combination of `and` and `or` logical operators should do it:
```
SELECT MAX(created_date) AS maxtime ,team_id, ticket_id
FROM ri_ticket_status_history
WHERE (status_id <> 7 AND team_id > 1) OR team_id = 1
GROUP BY team_id, ticket_id
``` | > brace location can change the result set.
```
select max(created_date) as maxtime ,TEAM_ID,ticket_id
from ri_ticket_status_history
where ( status_id<>7 or (status_id=7 and team_id=1))
group by TEAM_ID,ticket_id
``` | SQL query where clause filter based on another column value | [
"",
"sql",
"sql-server",
"oracle",
"select",
""
] |
Every time I confused for selecting varchar(max) or varchar(fix) datatype. suppose I have a data column that will be around 5000 varchar. a column is not null type.
should i set it varchar(max) not null or varchar(5000) not null.
same thing in case of a nullable data type.
```
CREATE TABLE [dbo].[tblCmsPages](
[CmsP... | [MSDN](https://msdn.microsoft.com/en-IN/library/ms176089.aspx)
* Use varchar when the sizes of the column data entries vary
considerably.
* Use varchar(max) when the sizes of the column data entries vary
considerably, and the size might exceed 8,000 bytes.
When the the length is specified in declaring a `VARCHAR`... | You have clear idea about data , it would be not exceed than 5000, I prefer to varchar(n)(varchar(5000).
If you want to selection between varchar(n) and varchar(max), please care below point:
1. Where appropriate, use VARCHAR(n) over VARCHAR(MAX)
a. for reasons of good design if not performance benefits, and
... | sql varchar(max) vs varchar(fix) | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need to select top 1 most valid discount for a given FriendId.
I have the following tables:
**DiscountTable** - describes different discount types
```
DiscountId, Percent, Type, Rank
1 , 20 , Friend, 2
2 , 10 , Overwrite, 1
```
Then I have another two tables (both list FriendI... | Having multiple tables of identical structure is usually bad practice, a single table with `ID` and `Type` would suffice, you could then use it in a `JOIN` to your `DiscountTable`:
```
;WITH cte AS (SELECT ID,[Type] = 'Friend'
FROM Friends
UNION ALL
SELECT ID,[Type] = 'Over... | This will get you all the FriendIds and the associate discount of the highest rank. It's an older hack that doesn't require using top or row numbering.
```
select
elig.FriendId,
min(Rank * 10000 + DiscountId) % 10000 as DiscountId
min(Rank * 10000 + Percent) % 10000 as Percent,
from
DiscountTable as d... | SQL Select with Priority | [
"",
"sql",
"sql-server",
"select",
""
] |
Suppose, we have query like this:
```
SELECT
1
FROM DUAL WHERE
(SELECT id FROM table_1 t1 WHERE /*conditions*/)
IN
(SELECT id FROM table_1 t2 WHERE /*conditions*/)
```
I want to check if first query
`SELECT id FROM table_1 t1 WHERE /*conditions*/`
returns the same ids like the second query.
Of course this query (`I... | This will return everything from the first set that is not also contained in the second set, or NULL if the second set contains every element of the first set:
```
SELECT id FROM table_1 t1 WHERE /*conditions*/
EXCEPT
SELECT id FROM table_1 t2 WHERE /*conditions*/
```
If the second set contains additional elements no... | Try:
```
SELECT id FROM table_1 t1 WHERE /*conditions1*/ and id not in (SELECT id FROM table_1 t2 WHERE /*conditions2*/)
union
SELECT id FROM table_1 t1 WHERE /*conditions2*/ and id not in (SELECT id FROM table_1 t2 WHERE /*conditions1*/)
```
If both queries gives you the same id's the result should be empty. | How to check if two selects return the same ids | [
"",
"sql",
""
] |
I'm trying to make an SQL query. I'm still new to SQL, maybe someone could give me some direction, or let me know if this is even possible.
Please note I have read up on IN, ALL, INNER JOIN etc and I still cannot get the proper query. I have tried to find the solution for hours.
These are my table columns:
```
+----... | Do a self join on the table (routes) on the column (stopName) and then get all the results where day=week and stopIds are not same. This would give you the answer to the first query
```
Select unq.stopId, unq.stopName from Routes unq join Routes other on other.stopName=unq.stopName where unq.stopId!= other.stopId and ... | With the query you are running you will return all stops as the nested query will always contain the stop from the outer query.
Use the following to stop this from happening.
```
SELECT stopID,stopName AS s1
FROM Routes
WHERE stopName IN (SELECT stopName AS s2
FROM Routes
WHERE ... | SQL matching column with another in same table, IN statement not working | [
"",
"mysql",
"sql",
""
] |
I have two tables
```
T1:
ID, Truck, Trailer
1 null null
2 null null
T2:
ID, Type, ResourceID
1 R 111
1 F 222
1 D 333
2 R 444
2 F 555
```
I need a result where
```
ID, Truck, Trailer
1 111 222
2 444 555
```
How can I update `T1.Truck = T2.ResourceID` when `T2.Type =... | The problem with your current update query is that the update will update one column to null as it can't match both conditions at the same time.
If you did a `select *` instead of the update the result would look like:
```
ID Truck Trailer Id Type ResourceId
1 NULL NULL 1 R 111 -- this will set... | you can `PIVOT` the table `t2` before updating the `t1` table
Use the following query to pivot the `t2` table.
```
SELECT ID, R, F
FROM t2
PIVOT (Max(resourceID)
FOR type IN ([R],[F]))pv
```
Now the result will in the format of `t1` table you can easily update using the following query
```
UPDATE A... | Update data where ID match and use case to choose what data | [
"",
"sql",
"sql-server",
"t-sql",
"sql-update",
""
] |
I have been trying to generate a series of dates (YYYY-MM-DD HH) from the first until the last date in a timestamp field. I've got the `generate_series()` I need, however running into an issue when trying to grab the start and end dates from a table. I have the following to give a rough idea:
```
with date1 as
(
SELEC... | You don't need a CTE for this, that would be more expensive than necessary.
And you don't need to cast to `timestamp`, the result already *is* of data type `timestamp` when you feed `timestamp` types to [`generate_series()`](https://www.postgresql.org/docs/current/functions-srf.html). Details here:
* [Generating tim... | How about using aggregation functions instead?
```
with dates as (
SELECT min(start_timestamp) as first_date, max(start_timestamp) as last_date
FROM header_table
)
select generate_series(first_date, last_date, '1 hour'::interval)::timestamp as date_hour
from dates;
```
Or even:
```
select generate_s... | Generate_series in Postgres from start and end date in a table | [
"",
"sql",
"postgresql",
"aggregate-functions",
"generate-series",
""
] |
I need two columns A and B but of them A has repeated values and B has single unique values. I have to fetch only those values of A which has max(C) value. C is another column. | Use `Row_Number` Analytic function to do this
```
select A,B
from
(
select row_number() over(partition by A order by C desc)rn,A,B,C
from yourtable
)
where RN=1
``` | You can use [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx "Row Number").
> **ROW\_NUMBER**
>
> Returns the sequential number of a row within a partition of a result
> set, starting at 1 for the first row in each partition.
>
> ---
>
> **PARTITION BY value\_expression**
>
> Divides the result set... | Remove multiple entries for a column | [
"",
"sql",
"oracle",
""
] |
I have one table and in this table is PostDate and OrderNo and a bunch of other fields. I would like to get all the latest PostDates and then with those PostDates get the largest OrderNo. I would then like to show one row that shows the PostDate and that OrderNo.
So far I below. This shows me all the rows with postdat... | If you just want the order number, you can use MAX again since you know the post date will also be the MAX due to your subselect:
```
SELECT MAX(OrderNo), MAX(PostDate)
FROM table
WHERE PostDate = (SELECT MAX(PostDate) FROM table)
``` | The simplest way to solve this problem is to drop the `WHERE` with the `MAX` altogether, order the rows in such a way that the row that you want is at the top, and limit the output to a single row.
The last step (limiting the output to one row) is dependent on SQL version. Here is how to do it in SQL Server:
```
SELE... | SQL - Nested Select Statements with Max? | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
I have two columns **created\_at** and **updated\_at** in same table. Both the columns have data type as **datetime**. Now when I am trying to modify the column data types as follows -
```
alter table nodestatics modify column updated_at datetime default current_timestamp;
alter table nodestatics modify column creat... | It is hard to reference [documentation](http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html) in a comment:
> As of MySQL 5.6.5, `TIMESTAMP` and `DATETIME` columns can be automatically
> initializated and updated to the current date and time (that is, the
> current timestamp). Before 5.6.5, this is tru... | Use `TIMESTAMP` instead of `DATETIME`
---
Should be something like this:
`ALTER TABLE nodestatics MODIFY COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;`
`ALTER TABLE nodestatics MODIFY COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;`
---
Or you can use `TRIGGERS`.
```
CREATE TRIGGER myTable_OnInse... | Column name is not taking timestamp as default value | [
"",
"mysql",
"sql",
"mysql-error-1067",
""
] |
I have a data that is`101.32650000` and I want to get `101.3265` only ... I tried using right function, but the disadvantage is that digits before decimal can vary. | How about using `cast` with `decimal` and scale of 4. Something like:
```
select cast(101.32650000 as decimal(10,4));
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!6/507e0/1) | ```
cast(col_name as decimal(28,4)) as col_name
``` | How to get 4 digit numbers after decimal including before decimal also in SQL | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I am using `MySQL 5.6.17`.
I have a `table` that contains the master entries of titles let us say it `Master_titles`. It contains columns `id int primary key auto-increment`, `title varchar(255)`. The data is as shown below :
```
id title
1 Item one
2 Item two
3 Item three
4 Item five
6 ... | According to your comment stating, that all the columns containing ids in table `data` are actually `ids` of `routines` table you need to perform joins to get title for every column by going through the path that is `routines > master_titles`.
```
SELECT
d.id,
d.routine_id,
mgroup.title group,
mquesti... | Just a small change from "Consider Me" answer.
```
SELECT
d.id,
d.routine_id,
mgroup.title group,
mquestion.title question,
manswer.title answer
FROM
data d
JOIN routines r1 ON ( d.group_id = r.id )
JOIN master_titles mgroup ON ( r1.master_title_id = m.id )
JOIN routines r2 ON ( d.... | MySQL Multiple column joins with more than one table references | [
"",
"mysql",
"sql",
"join",
""
] |
I'm displaying records of a table which I `COUNT` a particular field.
There might be sometimes the table might be empty and instead of displaying a `NULL` value i want it to come zero.
```
SELECT count(comment) as total
FROM dbo.omment
WHERE resp = MMColParam2
AND com_stat = 'No' having count(comment)> 0
``` | Taking a look at the documentation, you can use [ISNULL](https://msdn.microsoft.com/en-us//library/ms184325.aspx):
> ISNULL ( check\_expression , replacement\_value )
```
SELECT ISNULL(COUNT(comment), 0)) AS total
FROM dbo.omment
WHERE resp = MMColParam2
``` | You can use [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx), which "Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL". You pass to it **count(comment)** as the first argument, and **zero** as the second:
```
SELECT COA... | SQL-Query return zero count if no records are found | [
"",
"sql",
"sql-server",
""
] |
i have table named etablissement\_amenities
```
id
etablissement_id
amenities_id
```
I need to delete my duplicate row.
For example I have duplicate row like this.
```
id etablissement_id amenities_id
1 1 1
2 1 1
3 2 ... | This Query Will hopefuly delete all duplicated rows from `doublon`
```
DELETE FROM doublon WHERE id in
( Select id from `doublon` where `id` not in
( Select id
From `doublon`
group by etablissement_id,amenities_id
having Count(etablissement_id) > 1 and Count(amenities_id) > 1
... | There is no information about the table doublon u refered in the above query.
To delete or update a table with sub query referencing same table, try enclosing the subquery in a temporary derived table as follows.
```
DELETE FROM doublon
WHERE id < ANY (Select * from (SELECT etablissement_amenities.id
... | delete duplicate row on table | [
"",
"mysql",
"sql",
""
] |
I have an Oracle DB and there-in is a table, lets say "aura"

Now in this table there are different records with duplicates. I have to remove these duplicates.
As you can see in the image above **Dsvsd**, **Cvra**, **Single Entry** & **Double Entry*... | Here's one approach using `rowid` and the `row_number` ranking function to delete duplicates:
```
delete from auro
where rowid in
( select rwid
from ( select rowid rwid,
row_number() over ( partition by name
order by review_id desc) rn
from auro
... | ```
delete from aura where id not in (
select min(id) keep (dense_rank last order by review_id nulls first)
from aura
group by name
)
``` | Delete Query to remove duplicates and keep the latest record | [
"",
"sql",
"oracle",
""
] |
Thanks to NoDisplayName ([SQL: Query to set value based on group parameter](https://stackoverflow.com/questions/29020509/sql-query-to-set-value-based-on-group-parameter/29020724#29020724)) for getting my table to have Primary tags. But now I need help with a query to find errors in my table.
Sample Input:
```
Column1... | ```
select
column1,
column2,
count(column1)
from tablename
groupby column1, column2
having count(column1) > 1
``` | I think the following is the query you want:
```
select column1, count(column1)
from tablename
where column2 = 'Primary'
group by column1
having count(*) > 1;
```
This will pick up only duplicate values of `'Primary'`. It will not pick up duplicate blank values. | SQL: Find duplicated values associated with one ID | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
According to the first normal form, every row and column intersection contains exactly one value from the applicable domain.
If name is divided into three part First Name, Middle Name , Last Name.
For few value if I gave middle name as Null.
Does it violate the 1NF rule?
```
`````````````````````````````````````````... | This does not violate the 1st normal form. A violation of the first normal form would have more than one value for a column within the same row. Using your example, if someone changed their last name and you simply added a new distinct value to the same row, or you tossed in nicknames to the first name column like:
```... | E.F. Codd's definition of first normal form (1NF) was very simple:
> A relation [table] is in first normal form if it has the property that none of its domains [sets of possible values] has elements [values] which are themselves sets.
Under this definition it is obvious that first normal form does not preclude having... | First Normal Form - Exact one value rule | [
"",
"sql",
"oracle",
""
] |
```
Begin Tran
Declare @Ssql As Varchar(100)
Set @Ssql = 'India is mycountry. I love my country and I am proud of its rich and varied heritage'
Select charindex('country', lower(@Ssql))
RollBack
```
This query returns 12 and not 31.
Okay, now I want the char index of the word `country` [later] and not of the word ... | Try this
```
Begin Tran
Declare @Ssql As Varchar(100)
Set @Ssql = 'India is mycountry. I love my country and'
Select charindex(' country',lower(@Ssql))+1
RollBack
```
or try using the index start postion as
```
SELECT CHARINDEX('country', @Ssql, 14);
``` | The following code will give you the last occurrence of the `serachchar`. Using [REVERSE](https://msdn.microsoft.com/en-us/library/ms180040.aspx) function many times is detrimental to performance
```
DECLARE @Ssql VARCHAR(500) = 'India is my country. I love my country and I am proud of its rich and varied heritage'
DE... | How do I get the char index of an exact word in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I'm almost a newbie coming from the "Java's World" to the "PL/SQL World", working with "legacy" stored procedures, and I have a question.
Best practices for Java naming includes tips such as "the names of variables, methods, classes, etc should be meaningful and auto-documented" (I read on the Clean Coder book).
By def... | You should definitely make the names more readable, meaningful and auto-documenting. It would be hard to come across any language where a more descriptive name would be disadvantageous (maybe in some codegolf specific languages due to length constraints), at least in terms of performance. Sql and PL/Sql are no differen... | Variable names have no impact on performance.
Regardless of the language, variable names should be clear and self-documenting. Given that PL/SQL variable names are limited to 30 characters, however, making things clear and self-documenting may involve some sort of consistent abbreviation. If I know, for example, that ... | Does variables/functions/procedures/etc name affect performance in PL/SQL? | [
"",
"oracle",
"plsql",
"naming-conventions",
"sql",
""
] |
I am trying to pass the date as a where condition in select query.but in the database the field is in datetime format.I don't know how to pass the condition?
```
SELECT * FROM (`scl_students`) WHERE `std_added_on` = '2015-03-03'
``` | i got it.
```
SELECT * FROM (`scl_students`) WHERE DATE(std_added_on) = '2015-03-06'
``` | I guess the problem is that the `std_added_on` contains time portion which could be non-zero. In order to select all rows for a given date you would write:
```
SELECT *
FROM `scl_students`
WHERE `std_added_on` >= '2015-03-03'
AND `std_added_on` < '2015-03-03' + INTERVAL 1 DAY
```
This is better than `` DATE(`std_a... | sql condition as date and db date format is in datetime | [
"",
"mysql",
"sql",
"date",
"datetime",
""
] |
I'm trying to calculate a percentage in SQL. I want to find out to get the percentage of output start with 'RT @'
```
CREATE TABLE temp
([tweet] varchar(130)) ;
INSERT INTO temp
([tweet])
VALUES
('WillyWonka'),
('Barbara'),
('JoanOfArcJoanArcadia'),
('LisaDLisa Diddle'),
('LisaDSkip Pad... | You need `conditional Aggregate` to find the percentage of output start with `'RT @'`
```
SELECT ( Count(CASE WHEN tweet LIKE 'RT @%' THEN 1 END)
/ Cast(Count(*) AS NUMERIC(10, 2)) ) * 100
FROM temp
``` | You'll want a subquery to find the dividend. Something like this.
```
select (count(t.*) / (select count(*) from temp)) as percentage
from temp t
where tweet like 'RT @%'
``` | Calculating a percentage in SQL | [
"",
"sql",
"sql-server",
"count",
"division",
"percentage",
""
] |
I am trying to work out the `SQL` to average a series of numbers, but only to include those greater than 0.
For example:
```
Field
4
5
0
6
SELECT Avg(Field) FROM Table;
```
gives 3.75. But I want it to ignore the 0 so the average is 5.
```
SELECT Avg(Field) FROM Table where Field > 0;
```
works but what if I have... | You can use a conditional expression:
```
SELECT
Avg(case when Field1 > 0 then Field1 end),
Avg(case when Field2 > 0 then Field2 end)
FROM table
``` | Just filter out 0 using the where clause.
```
SELECT Avg(Field) FROM Table Where Field > 0
``` | Using SQL to work out the average of some, but not all, records | [
"",
"sql",
""
] |
It is Microsoft SQL Server.
In this column `PostalCode` from the AdventureWorks 2012 `Person.Address` table, there are numeric and string values.
I want to get table with rows `WHERE PostalCode < 7000`
This does not work as expected:
```
USE [AdventureWorks2012]
SELECT *
FROM Person.Address
WHERE ISNUMERIC(PostalC... | The error is being returned because the conditions being evaluated are not short-circuiting - the condition `PostalCode<7000` is being evaluated even where the postal code is non-numeric.
Instead, try:
```
SELECT *
from Person.Address
WHERE CASE WHEN PostalCode NOT LIKE '%[^0-9]%'
THEN CAST(PostalCode AS N... | If you're in SQL Server 2012 or newer you should use try\_convert instead of isnumeric. Isnumeric has some funny issues that it returns 1 even for strings that can't be converted into a number. So something like this should work:
```
SELECT *
FROM Person.Address
WHERE try_convert(int, PostalCode) < 7000
```
If the st... | Conversion failed. SELECT * from Person.Address WHERE ISNUMERIC(PostalCode) =1 AND PostalCode<7000 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a voting system and the tables look like this:
```
answers
-----------
int id
text content
results
-----------
int id
int answers_id
```
I want a select so i can see the answer and the number of responds even if there are no votes(results).
I tried something like this:
```
SELECT
count(results.answers_id), ... | This should do the job:
```
SELECT count(results.answer_id), answers.content
from answers left outer join results on answers.id = results.answer_id
group by answers.content;
``` | Try
```
SELECT
count(result.answers_id) as acount, answers.content
from answers
left inner join results
on answers.id = acount
``` | mySQL voting system SELECT | [
"",
"mysql",
"sql",
""
] |
I am trying to get the last element of an ordered set, stored in a database table. The ordering is defined by one of the columns in the table. Also the table contains multiple sets, so I want the last one for each of the sets.
As an example consider the following table:
```
benchmarks=# select id,sorter from aggtest ... | Why not use a window function:
```
select id, sorter
from (
select id, sorter,
row_number() over (partition by sorter order by id desc) as rn
from aggtest
) t
where rn = 1;
```
Or using Postgres `distinct on` operator which is usually faster:
```
select distinct on (sorter) id, sorter
from aggtest
o... | You write:
> Of course there is an easier way, to get the last (highest) id for
> each group by using the max aggregate. However, I am not so much
> interested in the id but as in data associated with it (i.e. in the
> same row).
This query will give you the data associated with the highest id of each sorter group.
... | Get last element of an ordered set in postgresql | [
"",
"sql",
"postgresql",
"aggregate-functions",
"greatest-n-per-group",
""
] |
I have two tables to join, and I want each row to be joined only once. Here is sample data:
```
CREATE TABLE A (id smallint, val varchar(1) );
CREATE TABLE B (id smallint, val varchar(1) );
INSERT INTO A VALUES (1, 'a'), (2, 'b'), (3, 'c'), (3, 'd');
INSERT INTO B VALUES (2, 'x'), (3, 'y'), (4, 'z'), (3, 'k');
```
Wh... | I could make it thanks to this [blog post](http://www.xaprb.com/blog/2005/09/27/simulating-the-sql-row_number-function/):
```
SELECT A2.id, A2.val, B2.val FROM (
SELECT l.id, l.val, COUNT(*) AS n1 FROM A AS l JOIN A AS r ON l.id = r.id AND l.val >= r.val GROUP BY l.id, l.val
) AS A2 JOIN (
SELECT l.id, l.val, ... | [SQL Fiddle](http://sqlfiddle.com/#!9/166bc/12)
**MySQL 5.6 Schema Setup**:
```
CREATE TABLE A (id smallint, val varchar(1) );
CREATE TABLE B (id smallint, val varchar(1) );
INSERT INTO A VALUES (1, 'a'), (2, 'b'), (3, 'c'), (3, 'd');
INSERT INTO B VALUES (2, 'x'), (3, 'y'), (4, 'z'), (3, 'k');
```
**Query 1**:
```... | JOIN each row only once — arrange (distribute) rows 1 to 1 | [
"",
"mysql",
"sql",
"join",
"row-number",
""
] |
Lets say we have quite a few tables (T1, T2... T50), and we would like to have n to n relations between all of them.
What would be a propper way of implementig that.
Having a relations table for each pair of Tx and Ty would not be practical if the number of tables goes up to 100 or more.
The current solution I have i... | The solution you proposed is the most reasonable solution to the stated problem. But the problem seems somewhat unreasonable.
If you need a graph, then you only need two tables, one for the nodes and another one for the edges.
If some nodes are of specific types then you can have extra specialization tables for them. | Add only the essential Relation tables. tblA relates to tblB, and tblB relates to tblC. So, *usually* that implies that you can get from A to C via
```
FROM tblA
JOIN tblB ON ...
JOIN tblC ON ...
```
Won't this do? And need not much more than 50 extra tables? And be a lot cleaner? | How to store a graph of sql tables | [
"",
"mysql",
"sql",
"database",
"performance",
"graph",
""
] |
I created an procedure to insert data from another table as follows:
```
DROP PROCEDURE IF EXISTS STP_addCompanySection;
DELIMITER //
CREATE PROCEDURE STP_addCompanySection ()
BEGIN
insert into companySection(categoryName,description)
select categoryName,description from BusinessCat where deleted='0';
END \g
DELIMI... | Try something like:
```
insert into companySection(categoryName,description,comId)
(select categoryName,description, inCompanyId
from BusinessCat
where deleted='0');
``` | You can do it this way:
```
insert into companySection(categoryName,description,comId)
select categoryName,description,inCompanyId from BusinessCat where deleted='0';
select LAST_INSERT_ID() id;
``` | insert into with select statement sql server | [
"",
"sql",
""
] |
I have so many records having duplicate taskid assigned to multiple person, but i want to show distinct records means only one taskid in output in SQL
Below is my query not working give me solution
```
SELECT DISTINCT
taskid, taskname, person, userid, dept, date, status, monitor,
comments, monitor_comments,... | i have added a column priority in which the value of that column is 1 of same TASKID and other will be 0 so i can find
SELECT DISTINCT
taskid, taskname, person, userid, dept, date, status, monitor,
comments, monitor\_comments, respondtime, assignedby,
reassigncomment, priority,date\_complete, followup\_date, re\_statu... | in your case, result is distinct but not of your desire because you need only distinct task id then you should use this:
```
SELECT DISTINCT taskid
FROM task
WHERE (status IS NULL)
```
then result would be distinct task ids. | Distinct Clause not working in SQL Server 2005 | [
"",
"sql",
"sql-server-2005",
""
] |
Shouldn't first\_value() ordered descending give the same results as last\_value() ordered ascending? I ran the following query and got the results attached below the query.
```
select random_date, trunc(random_date,'MM') random_month, random_value,
first_value(random_value) over (partition by trunc(random_date,'MM') ... | You forgot about a moving window used for analytical functions. See the difference (used rows between unbounded preceding and unbounded following):
```
SQL> select random_date, trunc(random_date,'MM') random_month, random_value,
2 first_value(random_value) over (partition by trunc(random_date,'MM') order by random_... | As I see you do first\_value this is used only for strings but you need it for a number so change it to min and max
In a string 10 will be before 2 but in number 2 is before | Should first_value() over (order by something asc) be the same as last_value () over (order by something desc)? | [
"",
"sql",
"oracle",
"sorting",
"analytic-functions",
""
] |
I have this simple SQL query :
```
UPDATE [mydb].[dbo].[EXPLANATIONS]
SET [EXPLANATION] = " This is the new explanation."
WHERE [RECORDNUMBER] = 123456
AND [EXPLANATIONNUMBER] = 7;
```
and I get this error :
> Msg 207, Level 16, State 1, Line 1
> Invalid column name ' This is the new explanation.' .
... | Double quotes are usually used to object names (e.g. column name). That is part of SQL-92 standard.
In ANSI SQL, double quotes quote object names (e.g. tables) which allows them to contain characters not otherwise permitted, or be the same as reserved words (Avoid this, really).
single quotes to the string litral
``... | Instead of using double quotes, use single quotes like:
```
SET [EXPLANATION] = '<i>new explanation</i>'
``` | Error in SQL UPDATE CLAUSE | [
"",
"sql",
"sql-server",
"sql-update",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.