Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Yesterday, I posted this question here: [MSSQL 2008: Get last updated record by specific field](https://stackoverflow.com/questions/26382131/mssql-2008-get-last-updated-record-by-specific-field/26382251)
Gordon Linoff came up with a good solution and I was happy until today, when I realized I posted only half of the s... | Try this should work with all your scenario..
```
;with cte
as
(
select rank() over(partition by fileid,contentid order by lastupdate ) id, ContentId,lastUpdate,FileId,IrrelevantField from tablename
)
select ContentId,lastUpdate,FileId,IrrelevantField from(
select row_number() over(partition by contentid order by last... | You were along the right lines changing it to an outer apply, then you can change the `WHERE` clause slightly to allow for records where there is no previous record.
```
SELECT c.ContentID,
c.LastUpdate,
c.FileID,
c.IrrelevantField,
FileID2 = c2.FileID
FROM Content AS c
OUT... | MSSQL 2008: Get last updated record by specific field (Part 2) | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have this query, it supposes to display data from current date (today) only
```
SELECT * FROM Customer WHERE visitTime <= GETDATE() AND visitTime > GETDATE() - 1
```
where *visitTime* is **datetime** type
But it doesn't work well because I think problem is at `AND visitTime > GETDATE() - 1` but I don't know how to... | Look at this example:
```
declare @visitTime datetime ='2014-10-16 23:59:59.000'
select GETDATE() GETDATE, @visitTime visitTime, GETDATE() - 1 [GETDATE-1]
GETDATE visitTime GETDATE-1
2014-10-17 00:02:18.980 2014-10-16 23:59:59.000 2014-10-16 00:02:18.980
```
You'll see that the visitti... | Assuming today is midnight last night to midnight tonight, you can use following condition
```
Select * from Customer where
visitTime >= DateAdd(d, Datediff(d,1, current_timestamp), 1)
and
visitTime < DateAdd(d, Datediff(d,0, current_timestamp), 1);
``` | SQL display | select data from today date | current day only | [
"",
"sql",
"sql-server",
"datetime",
""
] |
I'm wondering how I can return specific results depending on my first selected statement. Basically I have two IDs. CustBillToID and CustShipToID. If CustShipToID is not null I want to select that and all the records that are joined to it. If it is null default to the CustBillToID and all the results that are joined to... | For this, you basically want to build a string that is your SQL and then execute the string...look @ the answer to this one ::
[SQL conditional SELECT](https://stackoverflow.com/questions/1038435/sql-conditional-select) | You need a separate `case` for each column:
```
SELECT (CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.CustDesc ELSE c.CustDesc END) as CustDesc,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.Address1 ELSE c.Address1 END) as Address1,
(CASE WHEN cp.CustShipToID IS NOT NULL THEN cy.Address2 ELSE c.Addr... | Selecting columns based on a case SQL | [
"",
"sql",
"sql-server",
"sql-server-2012",
"conditional-statements",
""
] |
I have this query that will give me those rows that have the field "username" duplicated:
```
SELECT id, jos_users.username, email, password, lastvisitDate
FROM jos_users
INNER JOIN (SELECT username
FROM jos_users
GROUP BY username HAVING count(id) > 1) dup
ON jos_users.username =... | ```
SELECT id, jos_users.username, email, password, lastvisitDate
FROM jos_users
INNER JOIN (SELECT username
FROM jos_users jb
where jb.lastvisitDate =
(select min(jb1.lastvisitDate)
from jos_users jb1
where jb1.username = ... | I would probably write this as:
```
SELECT u.id, u.username, u.email, u.password, u.lastvisitDate
FROM jos_users u
WHERE EXISTS (SELECT 1 FROM jos_users WHERE username = u.username GROUP BY username HAVING count(id) > 1)
AND EXISTS (SELECT 1 FROM jos_users WHERE username = u.username GROUP BY username HAVING min(... | Find duplicate row get only the older one | [
"",
"mysql",
"sql",
""
] |
table [Status] has the following data:
```
ID Status
1 PaymentPending
2 Pending
3 Paid
4 Cancelled
5 Error
```
====================================
Data Table has the following structure:
```
ID WeekNumber StatusID
1 1 1
2 1 2
3 1 3
4 2 1... | A pivot might look like this:
```
SELECT * FROM
(SELECT
'Week ' + CAST(D.WeekNumber AS varchar(2)) [Week #],
S.Status
FROM DataTbl D
INNER JOIN Status S ON D.StatusID = S.ID
) Derived
PIVOT
(
COUNT(Status) FOR Status IN
([PaymentPending], [Pending], [Paid], [Cancelled]) -- add [Er... | ```
SELECT 'Week '+CAST(coun.WeekNumber AS VARCHAR(10)) [Week #],[PaymentPending],[Pending],[Paid],[Cancelled],[Error] FROM
(SELECT [WeekNumber],[Status] FROM dbo.WeekDetails
INNER JOIN [dbo].[Status] AS s
ON [dbo].[WeekDetails].[StatusID] = [s].[ID]) AS wee
PIVOT (COUNT(wee.[Status]) FOR wee.[Status]
IN ([PaymentPe... | How to use SQL Server 2005 Pivot based on lookup table | [
"",
"sql",
"sql-server",
"sql-server-2005",
"pivot",
""
] |
I just want to return a list from table where date difference more than 15 days are returned. It only returns where `RequestStatus=1` not getting from where `RequestStatus=2`.
Here is my query:
```
SELECT *
FROM User
WHERE RequestStatus = 1
OR RequestStatus = 3
AND (DATEDIFF(DAY, GETDATE(), TaskCompletionDat... | Use a SQL `IN` clause to specify all legitimate values for `RequestStatus` column in your `WHERE` condition like
```
Select *
from User
Where RequestStatus in (1,2,3)
and (DATEDIFF(day, getdate(), TaskCompletionDate))> 15
``` | I would suggest writing the query as:
```
select *
from User
Where RequestStatus in (1, 2, 3) and
TaskCompletionDate > DATEADD(day, 15, getdate())
```
By moving `TaskCompletionDate` outside the date functions, you give SQL Server more opportunities to optimize the query (for instance, by potentially making use ... | SQL Multiple conditions (AND, OR) in WHERE clause yield incorrect result | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I am trying to subtract 2 dates from each other but it seems that it is not subtracting properly and i am not sure what i am doing wrong here. I am using case statement to flag as 1 if the difference between the dates are less than 90 days else flag it as 0. But it is always flagging as 1 even if the difference between... | `extract` of a day returns the day element of a date. Since days are always between 1 and 31, the maximum difference is 30, and cannot be larger than 90.
Subtracting `date`s returns the difference in days, as an integer. So you need only drop the `extract` calls:
```
CASE WHEN (CAST(SVS_DT AS DATE) - CAST(DSCH_TS AS ... | you can use below one:
```
CASE WHEN (EXTRACT(EPOCH FROM (DATE_COLUMN_2 - DATE_COLUMN_1)) < (90*24*60*60)
THEN 1 ELSE 0 END AS FU90
```
here it returns the deference in seconds so you need to convert 90 days into seconds | Subtracting two dates using PostgreSQL | [
"",
"sql",
"postgresql",
"date",
""
] |
I have two tables in a MySQL database:
```
Book(title, publisher, year) title is primary key
Author(name, title) title is foreign key to Book
```
I am trying to select the name of the Authors that published a book each year from 2000 to 2005 inclusive. This SQL query works, but is there a way to do this that makes i... | Here's two ways to do it, and how another approach is wrong due to a subtle fault.
[SQL Fiddle](http://sqlfiddle.com/#!2/aa444f/2)
**MySQL 5.5.32 Schema Setup**:
```
create table Book (title varchar(10), year int) ;
create table Author (name varchar(10), title varchar(10));
insert Book values
('Book1',2000),('Book... | I would put an 'OR' clause in the where statement. It depends on how your table is set up but it should work:
```
SELECT DISTINCT name
FROM Author
WHERE name IN (SELECT Author.name
FROM Author INNER JOIN Book ON (Author.title = Book.title)
WHERE year = 2000)
``` | SQL Query: How to improve? | [
"",
"mysql",
"sql",
"relational-division",
""
] |
1.
```
select course_id
from course
where exists
(select course_id
from course
where course_id not in
(select course_id
from section));
```
2.
```
select course_id
from course
where course_id not in
(select course_id
from section);
```
I want to retrieve every `course_id` in t... | From docs:
```
If a subquery returns any rows at all, EXISTS subquery is TRUE, and NOT EXISTS subquery is FALSE
```
So in Your case, 1st query returns all rows casue it will looks like
```
select course_id from course where TRUE;
```
So if You want to retrieve every course\_id in table course that does not appear i... | Your first query simply returns all courses, as 115 courses always `EXIST` that are not in section table. Therefore, the `EXIST` clause is always true.
Just to show the difference, the following query should return 115 rows as your second one. But your second one is certainly more efficient.
```
select c1.course_id
f... | What is the different between the two sql codes? | [
"",
"sql",
"exists",
""
] |
I got this problem. When i tried to summarize the min quatity of nations's products and it did not work.
I have 2 tables below
PRODUCT:
```
ID|NAME |NaID|Qty
-------------------
01|Fruit|JP |50
02|MEAT |AUS |10
03|MANGA|JP |80
04|BOOK |AUS |8
```
NATION:
```
NaID |NAME
-------------------
AUS |Australia
JP |J... | SQL Server 2005 supports window functions, so you can do something like this:
```
select id,
name,
NaID,
name,
qty
from (
select p.id,
p.name,
p.NaID,
n.name,
min(P.Qty) over (partition by n.naid) as min_qty,
p.qty
from Product p
jo... | In Oracle, you can use several techniques. You can use subqueries and analytic functions, but the most efficient one is to use aggregate functions [MIN](http://docs.oracle.com/database/121/SQLRF/functions111.htm#SQLRF00667) and [FIRST](http://docs.oracle.com/database/121/SQLRF/functions073.htm#SQLRF00641).
Your tables... | SQL:How to get min Quantity? | [
"",
"sql",
"sql-server",
""
] |
I'm practicing a lab manual excercise in which I have to create 6 tables. Creation of 5 is
successful.
But one line is giving error
```
constraint GRADE_Designation_FK
FOREIGN KEY(Designation) References EMPLOYEE(Designation),
```
ERROR at line 7:
> ORA-02270: no matching unique or primary key for this column-l... | You've got the constraint on the wrong table. You should create a foreign key on EMPLOYEE.DESIGNATION, referencing back to GRADE.DESIGNATION.
So your tables should look something like:
```
create table GRADE
(
Designation varchar2(50) constraint GRADE_Designation_PK PRIMARY KEY,
Grade number(2),
TotalPosts number(4),... | > ORA-02270: no matching unique or primary key for this column-list
That error is very self explanatory and tells you what's wrong. In your case, you are trying to create foreign key on a non primary key column and so the error
```
constraint GRADE_Designation_FK FOREIGN KEY(Designation)
References EM... | error ORA-02270: no matching unique or primary key for this column-list | [
"",
"sql",
"database",
"oracle",
""
] |
I m try to make a Table using Create Table in SQL,
where a person can work at multiple places, and a place can have multiple person working on it,
this is what i m trying, i m sure its not correct
```
create table ( person char(15), place char(15), salary int)
```
now since a person can work in multiple places,... | You should create three separate tables:
```
"persons"
int ID (primary key, auto-increment)
varchar username
varchar email ... (all other info needed)
"places"
int ID (primary key, auto-increment)
varchar name
etc.
```
And the third table gives you the relationship between the two:
```
"person_places" (or place_per... | It is called a *n to m relation*. Use 3 tables
```
persons table
-------------
id int
name varchar
places table
------------
id int
name varchar
place_persons table
-------------------
place_id int
person_id int
``` | Creating a Table in SQL, where each tuple can have mutiple values | [
"",
"mysql",
"sql",
"database",
"create-table",
""
] |
I have the following data in my table:
```
SELECT category, value FROM test
```
```
| category | value |
+----------+-------+
| 1 | 1 |
| 1 | 3 |
| 1 | 4 |
| 1 | 8 |
```
Right now I am using two separate queries.
1. To get average:
```
SELECT category, avg(value... | AVG is also a windowed function:
```
select
distinct
category,
avg(value) over (partition by category) as average,
PERCENTILE_CONT(0.5)
WITHIN GROUP (ORDER BY value)
OVER (partition BY category) AS Median
from test
``` | I would approach this in a slightly different way:
```
select category, avg(value) as avg,
avg(case when 2 * seqnum in (cnt, cnt + 1, cnt + 2) then value end) as median
from (select t.*, row_number() over (partition by category order by value) as seqnum,
count(*) over (partition by category) as cnt... | Average and Median in one query in Sql Server 2012 | [
"",
"sql",
"sql-server",
"sql-server-2012",
"average",
"median",
""
] |
I have an "insert only" database, wherein records aren't physically updated, but rather logically updated by adding a new record, with a CRUD value, carrying a larger sequence. In this case, the "seq" (sequence) column is more in line with what you may consider a primary key, but the "id" is the logical identifier for ... | This is a clear case for *window* (or *OLAP*) functions, which are supported by all modern SQL databases. For example:
```
WITH
ORD_P
AS
(
SELECT p.*, ROW_NUMBER() OVER ( PARTITION BY id ORDER BY seq DESC) rn
FROM people p
)
,
NEW_P
AS
(
SELECT * from ORD_P
WHERE rn = 1
)
SELECT
*
FROM
... | I guess you already put it together. First find the max `seq` associated with each `id`, then use that to join back to the main table:
```
WITH newp AS (
SELECT id, MAX(seq) AS latestseq
FROM people
GROUP BY id
)
SELECT p.*
FROM people p
JOIN newp n ON (n.latestseq = p.seq)
ORDER BY p.id
```
What you ... | CTE to represent a logical table for the rows in a table which have the max value in one column | [
"",
"sql",
"db2",
"common-table-expression",
""
] |
**Requirements**:
1. Every employee has a unique ID. (EPID)
2. A employee can only be either one of below,
* FT - Full Time
* PT - Part Time
3. Any employee can never be both FT and PT.
4. FT & PT have lots of different fields to capture.
**Implementation**:
```
Create Table EmpFT( EPID int primary key, F1, F... | Try this method:
```
CREATE TABLE Emp(EPID INT PRIMARY KEY,
t CHAR(2) NOT NULL, UNIQUE (EPID,t));
CREATE TABLE EmpFT(EPID INT PRIMARY KEY, ... other columns
t CHAR(2) NOT NULL CHECK (t = 'FT'),
FOREIGN KEY (EPID,t) REFERENCES Emp (EPID,t));
CREATE TABLE EmpPT(EPID INT PRIMARY KEY, ... other columns
t... | You can add check constraints. Something like this for both tables
```
ALTER TABLE EmpFT
ADD CONSTRAINT chk_EmpFT_EPID CHECK (dbo.CHECK_EmpPT(EPID)= 0)
ALTER TABLE EmpPT
ADD CONSTRAINT chk_EmpPT_EPID CHECK (dbo.CHECK_EmpFT(EPID)= 0)
```
And the functions like so:
```
CREATE FUNCTION CHECK_EmpFT(@EPID int)
RETURNS in... | How do you enforce unique across 2 tables in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
"database-design",
""
] |
I am trying to get the count of certain types of records in a related table. I am using a left join.
So I have a query that isn't quite right and one that is returning the correct results. The correct results query has a higher execution cost. Id like to use the first approach, if I can correct the results. (see <http... | Typically fastest if you fetch **all or most rows**:
```
SELECT pp.id
, COALESCE(pt.a_dog_ct, 0) AS alive_dogs_count
, COALESCE(pt.a_cat_ct, 0) AS alive_cats_count
FROM people pp
LEFT JOIN (
SELECT person_id
, count(kind = 'dog' OR NULL) AS a_dog_ct
, count(kind = 'cat' OR NULL) AS a_c... | Your `WHERE alive=true` is actually filtering out record for `person_id = 2`. Use the below query, push the `WHERE alive=true` condition into the `CASE` condition as can be noticed here. See your modified [Fiddle](http://sqlfiddle.com/#!15/7c20b/11)
```
SELECT people.id,
pe.alive_dogs_count,
pe.alive_cats_count
FROM p... | Postgres LEFT JOIN with SUM, missing records | [
"",
"sql",
"postgresql",
"left-join",
"aggregate-functions",
""
] |
I am trying to group on column A but also order the groups by column B. I cannot get it to work. Also I want to join on another table.
```
select t.*, db_users.user as username, db_users.thumbnail
from
(
SELECT db_chats.* FROM db_chats WHERE db_chats.user = 'utQ8YDxD6kSrlI5QtFOUAE4h'
group by db_chats.partner ... | Assuming you after the last chat message from each partner for a given user...
We need to get a set of data that consists of the max time-stamp for each user partner (thus the inner select)
We then join this back to the chat table to get a all the additional desired attributes.
The reason why you're initial queries ... | ```
SELECT t1.* FROM db_chats t1
WHERE t1.user = 'utQ8YDxD6kSrlI5QtFOUAE4h'
AND NOT EXISTS (SELECT 1 FROM db_chats t2
WHERE t2.user = t1.user
AND t2.partner = t1.partner
AND t2.timestamp > t1.timestamp);
```
<http://sqlfiddle.com/#!2/4f44b/27> | Group by A but order by B | [
"",
"sql",
""
] |
I have two queries, the first one returns a movie and year which has movies which has more then two cast members and the second query displays the movies which have won more than two awards.
So I want to write a query which will give me the movie and year which occurs in one query but not both. How will I able to do t... | We can do this MINUS
First set is rows that exists in table1 alone
Second set is rows that exists only on table2
```
SELECT * FROM table1
MINUS
SELECT * FROM table2
UNION
SELECT * FROM table2
MINUS
SELECT * FROM table1
``` | > I want to write a query which will give me the movie and year which
> occurs in one query but not both.
To do this you need to do `UNION` of both the queries and `INTERCEPT` of both the queries AND `MINUS` the `INTERCEPT` from the `UNION`. Like this
```
((SELECT T2.movie_title,T2.release_year
FROM(SELECT b.movie_ti... | Movie and Year exist in one query but not both | [
"",
"sql",
"oracle10g",
"exists",
""
] |
Which one of the two would perform better(I was recently accused of not being careful with my code because I used the later in Oracle):
```
Select *
from Tab1
Where (not) exists(Select 1 From Tab2 Where Tab1.id = Tab2.id)
Select *
from Tab1
Where (not) exists(Select Field1 From Tab2 Where Tab1.id = Tab2.id)
```
O... | Yes, they are the same. `exists` checks if there is at least one row in the sub query. If so, it evaluates to `true`. The columns in the sub query don't matter in any way.
According to [MSDN](http://msdn.microsoft.com/en-us/library/ms188336.aspx), `exists`:
> Specifies a subquery to test for the existence of rows.
A... | I know this is old,but want to add few points i observed recently..
Even though exists checks for only existence ,when we write "select \*" all ,columns will be expanded,other than this slight overhead ,there are no differences.
Source:
<http://www.sqlskills.com/blogs/conor/exists-subqueries-select-1-vs-select/>
*... | Exists / not exists: 'select 1' vs 'select field' | [
"",
"sql",
"sql-server",
"oracle",
"exists",
""
] |
I am having problems increasing the prices of my hp products by 10%.
Here is what I've tried -->>
```
UPDATE products SET price = price*1.1;
from products
where prod_name like 'HP%'
```
Here is a picture of the products table:
 | This is your query:
```
UPDATE products SET price = price*1.1;
from products
where prod_name like 'HP%'
```
It has one issue with the semicolon in the second row. Also, it is not standard SQL (although this will work in some databases). The standard way of expressing this is:
```
update products
set price = pr... | This is an `UPDATE`, not a `SELECT`, so the `FROM` clause is incorrect. Also, the semicolon should go at the end of the last line.
```
UPDATE products SET price = price*1.1; <== Remove the semicolon
from products <== remove this line
where prod_name like 'HP%' <== add a semicolon at the end of this line
```
Try ... | Increase products price by 10% | [
"",
"mysql",
"sql",
"percentage",
""
] |
What I need to do is get the Highest `StockOnSite` per `ProductID` ( calculating the StockDifference ) record and concatenate StockOnSite with StockOffsite to create a column AllStock
I am completely lost? as I cannot group as we have a StockOnSite and StockOffsite
Here is the SQLFiddle
[Fiddle](http://sqlfiddle.com... | I believe this is the query you've been looking for.
It evaluates `StockDiff` as you suggested: `StockOnSite - StockOffSite` and then takes the highest value for every `SiteID`
```
SELECT
SiteID, Description, StockOnSite, StockOffsite, AllStock, LastStockUpdateDateTime, StockDiff
FROM (
SELECT
*,
rank() ... | You wanted to highest StockOnSite by ProductID, but the sample set all had unique productIDs. This query will get what you're asking for, but I think your question might be unclear as to what your result set needs to look like.
```
select pr.ProductID
, s.SiteID
,s.Description
,StockOnSite
,StockOffsite
,AllStock... | SQL Highest Value With Group | [
"",
"sql",
"sql-server",
""
] |
I have a oracle table like this
```
customer1 customer2 city
A B NY
B A NY
A C NY
A D NY
D A NY
C A NY
```
I am just interested in unique combination .
A B or B A etc
... | I don't know how to translate this to Oracle (if it is possible at all), but Postgres gives the short, if perhaps inefficient,
```
SELECT DISTINCT ON (LEAST(c1, c2), GREATEST(c1, c2))
LEAST(c1, c2), GREATEST(c1, c2), city FROM t;
``` | In Oracle you can do that:
```
SELECT DISTINCT LEAST(customer1, customer2),
GREATEST(customer1, customer2),
city
FROM T
```
See <http://sqlfiddle.com/#!4/b73ba/1>
Simple and easy to understand. But not be very efficient (can't use your index).
---
If you need to keep `customer1` an... | sql, how to eliminated repeated data across columns | [
"",
"sql",
"oracle",
""
] |
I am trying to create an insert statement, below is what I have so far:
```
INSERT INTO Role (application, developer, role)
VALUES (? ,
(SELECT Id from Developer WHERE firstName='Alice' and lastname='Wonderland'),
'ARCHITECT');
```
In the missing value field, I am trying to do a join, the following join statement... | I think this is what you are looking for:
```
INSERT INTO Role(application, developer, role)
SELECT a.id, (SELECT Id from Developer WHERE firstName = 'Alice' and lastname = 'Wonderland'),
'ARCHITECT'
FROM Application a JOIN
application d
ON d.id = a.id and a.category = 'GAMES';
``... | Incorporate your other parameters into your select statement
```
INSERT INTO Role (application, developer, role)
SELECT ?, Id, 'ARCHITECT' FROM Application a
JOIN application d ON d.id = a.id and a.category='GAMES'
``` | MySQL How do you INSERT INTO a table when a SELECT subquery returning multiple rows? | [
"",
"mysql",
"sql",
""
] |
I noticed on some test data that queries of the form
```
SELECT *
FROM a
JOIN b ON a.x = b.y
WHERE [more conditions...];
```
were returning the same data as queries of the form
```
SELECT *
FROM a,b
WHERE a.x = b.y
AND [more conditions...];
```
Intuitively they seem equivalent, but I'm not confident that this is th... | Both forms are equivalent but another reason why
```
SELECT *
FROM a
JOIN b ON a.x = b.y
WHERE [more conditions...];
```
is often preferred is that it offers more flexibility if you need to filter things a bit differently. Imagine for instance that x may be `null`. You have just to change the type of join to `left jo... | These queries are logically identical. The logical differences between the new `JOIN` form (SQL-92) and the older `,` form are in how the outer join expressions work.
Where they are not identical is in code quality. The SQL-89 form was superceeded by the SQL-92 over 20 years ago, and the newer form is much preferred f... | Is FROM x JOIN y ON x.a = y.b equivalent to FROM x,y WHERE x.a=y.b? | [
"",
"sql",
"performance",
"join",
"syntactic-sugar",
"equivalent",
""
] |
I'm trying to join 3 tables into a select statement but count the occurences of one while still showing the record if no occurences happen.
My example can be seen in the quick sqlFiddle that I've put together. I've tried to use left joins but it doesn't produce the result I want.
<http://sqlfiddle.com/#!6/e2840/8>
T... | Subselect answer:
```
SELECT O.OptionID,O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN
(
SELECT OPTIONID,USERID
FROM Answers WHERE QuestionID = 1
) AS A ON O.OptionID = A.OptionID
LEFT JOIN Users as U ON A.UserId = U.UserID
GROUP BY O.OptionID,O.OptionName
``` | You are using a WHERE clause with LEFT JOIN, which is making it act like an INNER JOIN.
Try this:
```
SELECT O.OptionID, O.OptionName, Count(A.OptionID) AS Total
FROM Options as O
LEFT JOIN Answers AS A ON O.OptionID = A.OptionID
and A.QuestionID = 1
LEFT JOIN Users as U ON A.UserId = U.UserID
GROUP B... | SQL Join to include NULL values | [
"",
"sql",
"sql-server",
"join",
"sql-server-2012",
""
] |
I have an insert statement similar to this:
```
insert into table (id, name, descr) values (4, 'asdf', 'this is not a word');
```
I need to insert this same statement with multiple ids. Right now I have:
```
insert into table (id, name, descr) values (4, 'asdf', 'this is not a word');
insert into table (id, name, de... | Use a `select . . . insert`:
```
insert into table(id, name, descr)
select i.id, 'asdf', 'this is not a word'
from (select 4 as id from dual union all
select 6 from dual union all
select 7 from dual union all
select 9 from dual
) i;
``` | ```
INSERT INTO [TableName] (id, name, descr) VALUES
(4, 'asdf', 'this is not a word'),
(6, 'asdf', 'this is not a word'),
(7, 'asdf', 'this is not a word'),
(9, 'asdf', 'this is not a word')
``` | Insert same data multiple times | [
"",
"sql",
"oracle",
"plsql",
""
] |
I'm trying to calculate responses for a questionnaire system. I want to show the result in one table (the question, options, number of responses). I wrote a query which works just fine however, it doesn't display all the options and if there are no responses for them.
My query
```
SELECT R.QuestionID, Q.Questio... | You need to use a `LEFT JOIN`, if you want to `display all the options and if there are no responses for them` like
**EDIT**
I have updated the answer based on your SQL fiddle. It works in [SQL Fiddle](http://sqlfiddle.com/#!6/4acf0/14) and gives you your desired output.
```
SELECT Q.QuestionName AS Question,
... | It could be something to do with your Inner joins. an Inner join produces only the set of records that match in both Table A and Table B.
Reviewing this might be of help <http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/> | SQL table joins query | [
"",
"sql",
""
] |
I'm trying to alter *(not best practice?)* a SQL server database's table that was installed by a piece of software.
**Goal:**
Set a constraint on a column to be a primary key then remove it.
**Notes:**
`APPT` - Table name
`ApptId` - Column that functions as a primary key (but was not set as the primary key b... | When you add primary key with out a name, SQL server generates a name for the constraint
So you are seeing the name as PK\_\_APPT\_\_EDACF695230515B9
In this case you need to use the generated name to drop the constraint
```
ALTER TABLE APPT DROP CONSTRAINT PK__APPT__EDACF695230515B9
```
When you added the Primary ... | Have you tried using the name of the constraint?
```
ALTER TABLE APPT DROP CONSTRAINT PK_APPT;
``` | Error 3728: is not a constraint | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
I am using the following command to output the result of an SQL query to a text file:
```
$sqlite3 my_db.sqlite "SELECT text FROM message;" > out.txt
```
This gives me output like this:
```
text for entry 1
text for entry 2
```
Unfortunately, this breaks down when the text contains a newline:
```
text for entry 1
... | In order to seperate columns, you would have to work with group\_concat and a seperator.
Query evolution:
```
SELECT text FROM messages;
SELECT GROUP_CONCAT(text, "=%=") FROM messages;
SELECT GROUP_CONCAT(text, "\r\n=%=\r\n") FROM messages;
// to get rid of the concat comma, use replace OR change seperator
SELECT ... | Try [-separator option](http://www.sqlite.org/sessions/sqlite.html) for this.
```
$sqlite3 -separator '=%=' my_db.sqlite "SELECT text FROM message;" > out.txt
```
**Update 1**
I quess this is because of '-list' default option. In order to turn this option off you need to change current mode.
This is a list of modes... | How can I specify the record delimiter to be used in SQLite's output? | [
"",
"sql",
"sqlite",
""
] |
Could you please help me with query to DB, i need to select products that have same combined ID's.
For example products with ID's 70 and 75. They both have filters 1 and 12.
IN wont work, it will also take #66 cuz it has filter 1 there, but second one is 11 and thats not what i need....
```
product_id | filter_id
... | Try this:
```
SELECT t1.*
FROM table AS t1
JOIN table AS t2 ON t1.product_id = t2.product_id
WHERE t1.filter = 1
AND t2.filter = 12
``` | ```
SELECT Product_ID
, Filter_ID
FROM Your_Table a
WHERE Filter_ID = 1
AND EXISTS (
SELECT NULL
FROM Your_Table b
WHERE Filter_ID = 12
AND b.Product_ID = a.Product_ID
)
``` | SQL select: fits both id's | [
"",
"mysql",
"sql",
""
] |
Read below and navigate to this url <http://sqlfiddle.com/#!2/e825f> to get a better understanding of my issue.
I have been trying to get this query right for awhile but cannot figure it out. I have been trying to join two tables to get the right data, but maybe I think I should make a third table. See my situation be... | Based on your description of the specification... "all mobile websites and responsive websites"...
I will suggest that something of this form may return the resultset you specified.
```
SELECT s.id
, s.websiteName
, s.url
, s.mobile_id
, s.is_responsive
, IF(m.mobile_url IS NOT NULL,'1','0') ... | Try something like this
```
select sites.* from sites
left join mobile on mobile.id = sites.mobile_id
where (sites.is_responsive = '1' or mobile_id is not null)
``` | SQL and Joining | [
"",
"mysql",
"sql",
"join",
""
] |
I have a column as
```
--------------------------------------------------------------
| Sl. No. | bal1 | bal2 | bal3 | status1 | status2 | status3 |
--------------------------------------------------------------
| 1 | 520 | 270 | 351 | 1 | 0 | 1 |
| 2 | 201 | 456 | 154 | 0 | ... | you can do it using `CASE`
[SQL Fiddle](http://www.sqlfiddle.com/#!3/3c0cf/4)
```
SELECT [SI. No.],
(case when status1 =1 then bal1 else 0 end +
case when status2 =1 then bal2 else 0 end +
case when status3 =1 then bal3 else 0 end) as balance
from Table1
``` | If the `status` values will always be 1 or 0, you can multiply and add:
```
select [Sl. No.], bal1 * status1 + bal2 * status2 + bal3 * status3
from table
``` | SQL Server : conditionally add rows and columns | [
"",
"sql",
"sql-server",
""
] |
We have these tables
```
CREATE TABLE tbl01
(
[id] int NOT NULL PRIMARY KEY,
[name] nvarchar(50) NOT NULL
)
CREATE TABLE tbl02
(
[subId] int NOT NULL PRIMARY KEY ,
[id] int NOT NULL REFERENCES tbl01(id),
[val] nvarchar(50) NULL,
[code] int NULL
)
```
If we run this query:
```
SELECT
tbl... | Use can use MAX and Group By to achieve this
```
SELECT id,
name,
MAX([val1]) [val-1],
MAX([val2]) [val-2]
FROM ( SELECT tbl01.id, tbl01.name,
CASE code
WHEN 1 THEN tbl02.val
ELSE ''
END [val1],
... | If there are always only two values, you could join them or even easier, group them:
```
SELECT tbl01.id as id, Min(tbl01.name) as name, MIN(tbl02.val) as val-1, MAX(tbl02.val) as val-2
FROM tbl01
INNER JOIN tbl02 ON tbl01.id = tbl02.id
GROUP BY tbl02.id
```
note: this query will always put the lowest value in t... | SQL Server, Merge two records in one record | [
"",
"sql",
"sql-server",
""
] |
I've been searching for a bit without finding anything. I'm not 100% at home with SQL but here's what I want to do:
```
SELECT TOP (SELECT COUNT (DISTINCT Name)
FROM Logg WHERE Id= 1)
* FROM Logg WHERE Id= 1
```
In other words, I want a single query, which first counts the number of rows with a distinct... | Your query does work - you just need to specify a column list:
```
SELECT TOP (SELECT COUNT (DISTINCT Name) FROM Logg WHERE Id= 1) * -- Need to specify columns
FROM Logg WHERE Id= 1;
```
[SqlFiddle](http://sqlfiddle.com/#!3/a0d06/1) | ```
SELECT TOP 1 * FROM Logg WHERE Id= 1
``` | How to specify a query for COUNT? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"select",
""
] |
In essence I have one table with two columns
```
One Two
-----------
A B
B C
C D
```
and I want to count the number of A's through D.
Resulting
```
Letter Count
---------------
A 1
B 2
C 2
D 1
```
My code now is
```
Select one, coun... | Try this
```
SELECT Count(a),
a
FROM (SELECT cola a
FROM table
UNION ALL
SELECT colb a
FROM table) c
GROUP BY a
``` | there is no reason to group twice.
```
select letter, count(*) as total_cnt
from
(
Select one as letter from table
union all
Select two as letter from table
)
group by letter;
``` | Counting from 2 columns in SQL server | [
"",
"sql",
"sql-server",
""
] |
Im developing android app, which use SQLite database.
I have **ListView** which uses data from Database to show a list (see picture).
The picture is decoded in Base64 String and stored in Database. My problem is this Log:
```
10-19 16:51:36.612: W/CursorWindow(15151): Window is full:
requested allocation 136877 byt... | Use the rawQuery method, and specify the limit keyword.
e.g.:
```
"SELECT * FROM myTable limit 10" <-- get the 1st 10 rows
"SELECT * FROM myTable limit 10, 20" <-- get the 2nd 10 rows between 10 and 20, etc
```
This should get you started. | I tried the answer above and the result was:
```
"SELECT * FROM myTable limit 10" <-- Got the first 10 rows
"SELECT * FROM myTable limit 10, 20" <-- Got the first 20 rows !
```
So the answer above did not work for me, what worked for me was this:
This is my table:
[](htt... | Sqlite Get x rows, then next x rows | [
"",
"android",
"sql",
""
] |
I have the following table `MyTable`:
```
id │ value_two │ value_three │ value_four
────┼───────────┼─────────────┼────────────
1 │ a │ A │ AA
2 │ a │ A2 │ AA2
3 │ b │ A3 │ AA3
4 │ a │ A4 │ AA4
5 │ b │ A5 │ AA5
```
I wan... | ### [`json_build_object()`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-CREATION-TABLE) in Postgres 9.4 or newer
Or [`jsonb_build_object()`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-CREATION-TABLE) to return `jsonb`.
```
SELECT val2, json_agg(json_build... | **to\_json** with **array\_agg** with **composite type**
```
begin;
create table mytable(
id bigint, value_two text, value_three text, value_four text);
insert into mytable(id,value_two, value_three,value_four)
values
( 1, 'a', 'A', 'AA'),
(2, 'a' , 'A2' , 'AA2'),
(3, 'b' , ... | Return multiple columns of the same row as JSON array of objects | [
"",
"sql",
"arrays",
"json",
"postgresql",
"aggregate-functions",
""
] |
I have a requirement , to get the out put in the following format when we give two dates as input:
* Input 1 --> `sysdate`
* Input 2 --> `to_date('10-OCT-2014')` --> this is dynamic
Output :
```
11 days 00 Hours 27 Minutes 41 Seconds
```
The seconds could be an optional one.
currently am using
```
select TRIM (TR... | I always appreciate questions related to datetime formatting with SQL. There are so many stupid hacks in the world (e.g. converting to strings and doing string operations)....
As your question is oracle specific, the answer by Multisync should be accepted. But if someone looks for a version that does not need the numt... | ```
select extract(day from ds_int) || ' days '
|| extract(hour from ds_int) || ' Hours '
|| extract(minute from ds_int) || ' Minutes '
|| extract(second from ds_int) || ' Second'
from
(select numtodsinterval(sysdate - to_date('10-10-2014', 'DD-MM-YYYY'), 'day') ds_int from dual);
```
With trailing ... | Formatting date (difference )- Oracle | [
"",
"sql",
"oracle",
""
] |
I have a concatenation in a query that takes values from different fields and creates the product name. My issue here is I need to keep the name under 80 characters, so if it passes 80 characters there
are certain key words in the "name" that I should be able to delete. For example
```
Oracle Lights 79-80 American Mot... | ok thanks to Phicon for pushing me in the right direction. I created a function that takes a string and checks its length, then takes out "Lights" if the string is over 80 characters, and "Oracle" afterward if it's still over 80 characters, then called it in an update query.
```
Public Function shortname(value As Stri... | You could try the follwing in the vba.
```
if len(yourfield) > 80 then Replace(yourfield, "Lights ", "") end if
if len(yourfield) > 80 then Replace(yourfield, "Oracle ", "") end if
``` | Deleting certain words depending on length of the value | [
"",
"sql",
"ms-access",
"vba",
"ms-access-2013",
""
] |
I have four tables `Customer`, `Sales`, `Invoice`, and `Receipt`.
## Customer
```
ID Name
1 A
```
## Sales
```
ID Name
1 Ben
```
## Invoice
```
ID Amt Date CustomerID SalesID
1 12 1/9/2014 1 1
2 10 1/10/2014 1 ... | You can get month wise total receipt and invoice amount by grouping and sub query like below :
```
SELECT Invoice.CustomerID [CustomerID],
Invoice.SalesID [SalesID],
SUM(Invoice.Amt) [Invoice_Amt],
ISNULL((SELECT SUM(Amt)
FROM Receipt
WHERE Customer... | Frankly, since you're just selecting customer and sales IDs (as opposed to names), you don't even need to joint all four tables:
```
SELECT i.CustomerID,
i.SalesID,
SUM(i.Amt) AS InvAmt,
SUM(r.Amt) AS RepAmt,
MONTH(i.`Date`) AS `Month`
FROM Invoice i
JOIN Receipt r ON ... | SQL - Join multiple table | [
"",
"sql",
"sql-server",
"join",
""
] |
I faced an interview and below is the question. The tables are below
Table1: Book (BookId is primary key)
```
BookId | Book_Title
1 | Book1
2 | Book2
3 | Book3
4 | Book4
5 | Book5
```
Table2: Book\_Copies
```
BookId | BranchId | No_of_copies
1 1 ... | Try This
```
SELECT B.Book_Title
From Book B LEFT JOIN book_copies BC ON B.Bookid = BC.Bookid
Group By B.Book_Title
Having SUM(ISNULL(BC.no_of_copies,0)) = 0
```
**[FIddle Demo](http://sqlfiddle.com/#!6/4da44/2)**
**Output:**
```
BOOK_TITLE
Book3
Book4
Book5
``` | You want books with no stock. I would approach this with a `left outer join`, aggregation, and a `having` clause:
```
select b.bookid, b.book_title
from book b left join
book_copies bc
on b.bookid = bc.bookid
group by b.bookid, b.book_title
having coalesce(sum(bc.no_of_copies), 0) = 0;
``` | SQL interview- how to get the record if there is no record or count is zero using multiple tables | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
I need to perform a query to get the candies that are most liked by kids and here's what I've got:
```
SELECT COUNT(*) as counts,candies.name
FROM candies
INNER JOIN kid_candy ON kid_candy.candy_id = candies.id
INNER JOIN kids ON kids.id = kid_candy.kid_id
GROUP BY candies.name
```
which would return:
```
counts |... | Assuming **a classical n:m relationship** between kids and candies like detailed here:
* [How to implement a many-to-many relationship in PostgreSQL?](https://stackoverflow.com/questions/9789736/how-to-implement-a-many-to-many-relationship-in-postgresql/9790225#9790225)
You should provide such details in your questio... | So, first lets get the counts per candy name (`tmp_table`), then get the max count of all candies (`max_cnt`) and finally put it all together and get the candies from `tmp_table` which have a count equal to `max(counts)` from `max_cnt` table...
```
with tmp_table AS (
select COUNT(*) as counts,candies.name as c_n... | Get rows with maximum count | [
"",
"sql",
"postgresql",
"aggregate-functions",
"greatest-n-per-group",
""
] |
Is it possible to select only the id's of the users that have admin role(role id = 3) without using NOT IN(same query with roleid)?
Each user has different roles(user, manager, admin, etc).
```
SELECT appUserInGroups.UserId, appRoles.RoleName, appRoles.RoleId
FROM appGroupInRoles
INNER JOIN appRoles ON app... | Try this:
```
WITH Admins AS
(
SELECT appUserInGroups.UserId AS uID
FROM appGroupInRoles
INNER JOIN appUserInGroups ON appGroupInRoles.GroupId = appUserInGroups.GroupId
WHERE appGroupInRoles.RoleId = 3
)
SELECT appUserInGroups.UserId, appRoles.RoleName, appRoles.RoleId
FROM appGroupInRoles
INNER JOIN ap... | Try an exclusion join:
```
SELECT u.UserId, r.RoleName, r.RoleId
FROM appUserInGroups u
INNER JOIN appGroupInRoles g on g.GroupId = u.GroupId
INNER JOIN appRoles r ON r.RoleId = g.RoleId
LEFT JOIN (
--Admin Users
SELECT u.UserId
FROM appUserInGroups u
INNER JOIN appGroupInRoles g on g.GroupId = u.Group... | Not selecting userId if not in role (admin), multiple roles in one user | [
"",
"sql",
"sql-server",
""
] |
I'm working on a big database and i'm seeking for everything that can speed up the database. The question is : when you have an unique index on somes fields, what is the faster between make a select request to check if it's ok, or try it anyway and catch the exception if the entry already exists ?
I made some research... | A manual check won't do what you think it does. (See below.)
If you check first, *every* insert requires two round-trips to the database. It might also require serializable transactions.
And you have to trap errors anyway. A duplicate value is just *one* thing that can go wrong on an insert; there are a *lot* of othe... | you have 2 choices
1. Try to insert and if the query fails, you will catch and roll back transaction.
2. Try to query once to check if it exists or not. If it does not exist,Insert the value.
In my opinion, first one is better because you use network connection twice if you query twice. Also select is an good option ... | SQL unique : manual check vs catch exception | [
"",
"sql",
"unique",
""
] |
I am using SQL Server.
I have a table with the following design:
```
ID bigint
Number varchar(50)
Processed int
```
I have a lot of duplicates in the Number column
I want to delete all repeated Numbers, and keep the Number `where processed=1`
For Example if I have
```
Number --- Processed
111 --- 0
111 --... | If you are just trying to delete the rows where number equals 111 and processed does not equal 1 you can do:
```
delete from <table>
where
Number = 111 and
Processed <> 1
```
Assuming the ID is sequential and you want to keep the last row for each Number you can do:
```
delete from <table> t
left join (
select... | Here is one method:
```
with todelete as (
select t.*,
row_number() over (partition by number order by processed desc) as seqnum
from table t
)
delete from todelete
where seqnum > 1;
```
The `row_number()` enumerates the rows, using the processed as a priority. The logic ensures that... | Delete duplicates and keep one with condition in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a query with a bunch of OR's inside an AND in the where clause and I'm trying to replace them with CASE WHEN to see if it improves the performance.
The select query inside the stored procedure is something like:
```
DECLARE @word = '%word%' --These are inputs
DECLARE @type = 'type'
SELECT * FROM table1
WHERE ... | There are is a lot of info online about these 'optional' type stored procedures and how to avoid parameter sniffing performance issues.
This syntax should get you closer though:
```
AND CASE
WHEN @type = 'CS' THEN col1
WHEN @type = 'ED' THEN col2
END LIKE @word
```
Just make sure the col1 and col2 datat... | You can also try nested case statements. e.g. based on your latest post, something like:
```
1 = CASE WHEN @type = 'CandidateStatus'
THEN (CASE WHEN co.[Description] LIKE @text THEN 1 END)
...
END
``` | CASE WHEN in WHERE with LIKE condition instead of 1 | [
"",
"sql",
"sql-server",
"performance",
"t-sql",
"stored-procedures",
""
] |
I have something like this:
```
SELECT cars.brand, cars.id FROM cars WHERE cars.brand = 4 LIMIT 1;
SELECT cars.brand, cars.id FROM cars WHERE cars.brand = 24 LIMIT 1;
SELECT cars.brand, cars.id FROM cars WHERE cars.brand = 29 LIMIT 1;
```
If will be more queries it will be very long.
How do this in the other way, in ... | You are worried about having to send so many queries one by one, so that would take a lot of time. You can make this one query instead:
```
SELECT cars.brand, cars.id FROM cars WHERE cars.brand = 4 LIMIT 1
UNION ALL
SELECT cars.brand, cars.id FROM cars WHERE cars.brand = 24 LIMIT 1
UNION ALL
SELECT cars.brand, cars.id... | ```
$ids = (4, 24, 29);
$limit = 1;
foreach ($ids as $id){
$query = "SELECT cars.brand, cars.id FROM cars WHERE cars.brand = $id LIMIT $limit";
// perform query
// store result
}
``` | How do this SQL queries cleaner, better, in one query? | [
"",
"mysql",
"sql",
"limit",
"distinct",
"greatest-n-per-group",
""
] |
I needed some help with doing a task in a clever way. I want pick out the very first movement on customer number and sales day and the same thing but for their last movement.
Is there someway of doing this?
These are the column names:
* Cust\_no
* type of sale
* sales day
* activation day
* campaign name
* seller na... | You can select both rows using a subquery
```
SELECT *
FROM
( SELECT *, ROW_NUMBER() OVER (PARTITION BY cust_no ORDER BY sales day ASC) as seq1,
ROW_NUMBER() OVER (PARTITION BY cust_no ORDER BY sales day DESC) as seq2,
) T
where T.seq1 =1 or T.seq2 =1
``` | try this
```
SELECT *
FROM tablename A
JOIN (SELECT cust_no,
Min(sales_day) min_sal,
Max(sales_day) AS max_sal
FROM tablename) B
ON a.cust_no = b.cust_no
AND ( a.sales_day = b.min_sal
OR a.sales_day = b.max_sal )
``... | Finding first and last customer movement SQL Server - tips? | [
"",
"sql",
"sql-server",
""
] |
I have a string like `A12345678B`
I want to be able to check if a string starts with a character, is followed by 8 digits and ends with a character.
We are trying:
```
SELECT REGEXP_INSTR('A12345678B', '[[:alpha:]]{1}[[:digit:]]{8}[[:alpha:]]{10}',1,1,1,'i') from DUAL
```
This returns :
```
11
```
We want to be a... | > string starts with a character
```
^[[:alpha:]]
```
> is followed by 8 digits
```
[[:digit:]]{8}
```
> ends with a character
```
[[:alpha:]]$
```
So the complete regex would be,
```
^[[:alpha:]][[:digit:]]{8}[[:alpha:]]$
```
This `[[:alpha:]]{10}` in your regex assumes that there must be exactly 10 alphabets ... | Try using `regexp_like` if you want a full string match. For a match, use:
```
WHERE REGEXP_LIKE('A12345678B', '^[[:alpha:]]{1}[[:digit:]]{8}[[:alpha:]]{1}$')
```
For a non-match use:
```
WHERE NOT REGEXP_LIKE('A12345678B', '^[[:alpha:]]{1}[[:digit:]]{8}[[:alpha:]]{1}$')
```
Note: this assumes that you want to filt... | How can I search for occurences in a string with Oracle REGEXP_INSTR | [
"",
"sql",
"regex",
"string",
"oracle",
""
] |
I have a VERY LARGE table with a timestamp and a value V. Some of the Vs might be null:
```
timestamp,V
sometime_1,value1
sometime_2,value2
sometime_3,NULL
sometime_4,value4
```
I want a query to select the value V of a given timestamp T, but if it is NULL, get me the value at the time closest to T on either side of ... | Similar to @par solution but with time:
```
SELECT v
FROM (
(SELECT v, TIMEDIFF(T, `timestamp`) AS tdiff
FROM table_name
WHERE `timestamp` <= T AND v IS NOT NULL
ORDER BY `timestamp` DESC
LIMIT 1)
UNION ALL
(SELECT v, TIMEDIFF(`timestamp`, T) AS tdiff
FROM table_name
WHERE `timestamp` > T AND v IS ... | You can create a VIEW like
```
SELECT T2.T,T2.V FROM TAB AS T2 WHERE T2.V IS NOT NULL
UNION
SELECT T0.T,(
SELECT T1.V FROM TAB AS T1 WHERE T1.V IS NOT NULL
ORDER BY ABS(T0.T-T1.T) LIMIT 1
) FROM TAB AS T0 WHERE T0.V IS NULL;
```
The clause
```
ORDER BY ABS(T0.T-T1.T)
```
of course ... | select closest non null value to timestamp | [
"",
"mysql",
"sql",
""
] |
I have a table of images with the some column like this: `id, path, name, likeCount`
I want to have a query that select an image by random between those 20 images with the highest `likeCount` .
Do you have any idea? | In that case, you need to do that in 2 steps:
First, you need to create a view in which you store the 20 first images with the highest `likeCount`:
```
CREATE VIEW first_Twenty_images AS
SELECT *
FROM images_table
ORDER BY likeCount DESC
LIMIT 20
```
After that, you can select a random element fr... | Try like this Not Tested.
```
Select * from ( select @a:=@a+1 no, id, path, name, likeCount from
table1,(SELECT @a:= 0) AS a order by likeCount desc limit 20 ) as tt order by
Floor(RAND() * 20) limit 1
``` | how to select some record by random between the some records? | [
"",
"mysql",
"sql",
"select",
"random",
""
] |
I'm trying to write a query that gives total numbers of unmatched letters between two strings.
For example, I have the given two strings
> String 1: Jamess String 2: Romeeo
I need to find out total number of letters in the second string that don't having a matching in the first string.
The letters would be
> R, o,... | Amusing puzzle game ;)
Using the analytic function `COUNT()` and by partitioning up to the current row, you are in fact able to "number yours letters":
```
SELECT letters,
COUNT(*) OVER (PARTITION BY letters ORDER BY n ROWS
BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cnt FROM (
... | **In Oracle**,
```
SQL> WITH DATA AS
2 ( SELECT 'Jamess' str1, 'Romeeo' str2 FROM dual
3 ),
4 data2 AS
5 (SELECT SUBSTR(str1, LEVEL, 1) str1
6 FROM DATA
7 CONNECT BY LEVEL <= LENGTH(str1)
8 ),
9 data3 AS
10 (SELECT SUBSTR(str2, LEVEL, 1) str2
11 FROM DATA
12 CONN... | Find Unmatching Letters between Two Strings | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have a user table which contains among others money, level and ranking.
```
Id | money| ranking| level
---------------------------
1 |30000| 1 1
2 |20000| 2 3
3 |10000| 3 2
4 |50000| 4 2
```
I want to update the ranking field based on user level (first filter) and mon... | As a side note, I would NOT store this field within the database - storing values that are dependent on other records in the table make maintenance much more difficult.
Here's a query that would work as a view or within a stored procedure:
```
SELECT
ID,
[money],
ROW_NUMBER() OVER (order by [level] desc,... | If you simply want to select then here is the query :
```
select *, dense_rank() over (order by level desc, mony desc) as newranking from YourTable
```
and if you want to update then :
```
;with cte_toupdate (ranking, newranking)
as (
select ranking, dense_rank() over (order by level desc, mony desc) as newranking f... | Updating field based on sorting of another | [
"",
"sql",
"sql-server",
""
] |
For example I have a table with orders. The table has a key (Order.No), a date where the order was opened (Order.Open) and a date where the order was closed (Order.Close).
```
No Open Close
--------- ---------- ----------
2013-1208 2013-03-11 2013-03-26
2013-1272 2013-03-11 2013-03-11
2013-127... | You can just enter the list of months/years you require and join to them, e.g.
```
SELECT [Open] = COUNT(o.No),
[Month] = DATEPART(MONTH, d.[Date]),
[Year] = DATEPART(YEAR, d.[Date])
FROM (VALUES
('2013-01-01'),
('2013-02-01'),
('2013-03-01'),
('2013-... | First generate all months you want to see in your results. Then join each month with the open orders and count per month.
```
with months as
(
select
datefromparts(year(min(opened)), month(min(opened)), 1) as startdate
from orders
union all
select
dateadd(month, 1, startdate)
from months
where dat... | GROUP BY Conditions | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have two tables, tbl1 and tbl2 as below:
```
CREATE TABLE tbl1 (`uid` int);
INSERT INTO tbl1 (`uid`)
VALUES
(100),
(200),
(300),
(400);
CREATE TABLE tbl2 (`id` int, `uid` int, `status` int);
INSERT INTO tbl2 (`id`, `uid`, `status`)
VALUES
(1, 100, 0),
(2, 100, 1),
(3, 100, 2),
(4, ... | You need to select uids with status=0 but not the ones that appear in your table also with status=1. So you need to exclude them from the result set. You need one more condition in your where clause to have the expected result. This can be done by using NOT IN.
Try the following query
```
SELECT tbl1.uid, tbl2.id, t... | you can use `NOT EXISTS` clause
```
SELECT DISTINCT T1.uid, T2.id, T2.status
FROM tbl1 T1
INNER JOIN tbl2 T2 ON (T1.uid = T2.uid)
WHERE T2.status = 0
AND NOT EXISTS ( SELECT 1 FROM tbl2 T22
where T2.uid = T22.uid
and T22.status =1 )
``` | SQL query to implement multiple WHERE condition on same column | [
"",
"mysql",
"sql",
""
] |
I'm currently working with a database containing the following schema:

Here are the tasks I'm required to carry out:

For task 1, I formulated the following query (inclusion of avg(salary) was for testing purposes):
```
sel... | you can do male employee count using CASE
Also converted explicit join ( comma separated tables in FROM CLAUSE) to implicit join
```
select D.dname, count(case when E.sex='M' then 1 else 0), avg(E.salary)
from department D
join employee E
on E.dno = D.dnumber
group by D.dname
having avg(Esalary)>30000;
```
As p... | This can also be done by evaluating the overall average in a subquery, derived table or cte per department before applying it to the filtered employees. Also note the preference for joining in `join` not in the `where`.
```
with cteSalary as
(
select dname, dno, avg(salary) as avgSalary
from department inner j... | Oracle SQL Nested Statement Issue | [
"",
"sql",
"oracle",
""
] |
I need to update a single column from a backup version of a database. I've restored the backup to a different db location and am running the following:
```
update table_name
Set
column = restoredDB.dbo.table_name.column
From restoredDB.dbo.table_name
Where restoredDB.dbo.table.ID = table_name.ID
```
The followi... | All you need for column refernces is the TableName.ColumnName:
```
update table_name
Set
column = table_name.column
From restoredDB.dbo.table_name
Where table.ID = table_name.ID
```
Also, in your `Where table.id =` expression, you do not have any table name `table` in your example query. | I think this should resolve the issue.
```
USE [<table_name_DB_Name>]
GO
UPDATE table_name
SET
column = t1.column
From restoredDB.dbo.table_name t1, table_name t2
Where t1.ID = t2.ID
``` | update table - multi-part identifier could not be bound | [
"",
"sql",
"sql-server-2012",
""
] |
I have the below query where I'm trying to calculate sum of salaries for over a period of year..
```
select sum(case when date_key between to_char(sysdate,'yyyymm')
and to_char(add_months(sysdate,-12), 'yyyymm')
then salary end) as annual_salary
from employee
group by... | ```
select sum(case when date_key between
to_char(add_months(sysdate,-12), 'yyyymm') and to_char(sysdate,'yyyymm')
then salary end) as annual_salary
from employee
group by emp_key
``` | Just invert the 2 bounds, they are not in the correct order:
```
...
between to_char(add_months(sysdate,-12), 'yyyymm')
and to_char(sysdate,'yyyymm')
``` | Aggregation between dates | [
"",
"sql",
"oracle",
"aggregation",
""
] |
Given a table of the following format:
```
Name | Value
A | 0
B | 0
C | 1
D | 2
E | 3
```
How could I query this table in this format:
```
SELECT value,count(*) FROM table GROUP BY value
```
Such that we produced the result:
```
Value | Count
0.. 1 | 3
2 | 1
3 | 1
`... | Use a case construct:
```
SELECT
CASE WHEN value IN (0,1) THEN '0..1' ELSE CAST(value AS CHAR(10)) END as values,
count(*)
FROM mytable
GROUP BY CASE WHEN value IN (0,1) THEN '0..1' ELSE CAST(value AS CHAR) END;
``` | Two solutions comes in to my mind:
First is to use a function for grouping the values
```
SELECT some_function(value) v, count(*) c FROM table GROUP BY some_function(value);
```
The other way is to join the mapping table with group and group relation mappings. | Grouping values by custom rules | [
"",
"mysql",
"sql",
"group-by",
""
] |
I am running the following code to extract all relevant rows from all tables that have a particular column. The outer `IF` is supposed to check if the column exists on the table for that iteration. If not, it should finish that iteration and move to the next table. If the table has the `GCRecord` column, it should then... | Use Dynamic query inside begin to avoid inner pre-compilation of code, for tables do not contain column '`GCRecord`'
```
USE WS_Live
GO
EXECUTE sp_MSforeachtable
'
IF EXISTS( SELECT *
FROM sys.columns
WHERE columns.Object_ID = Object_ID(''?'')
AND Name = ''GCReco... | You are very close. Use "EXEC"
```
USE WS_Live
EXECUTE sp_MSforeachtable
'
USE WS_Live
IF EXISTS( SELECT *
FROM sys.columns
WHERE columns.Object_ID = Object_ID(''?'')
AND Name = ''GCRecord''
)
BEGIN
EXEC(''SELECT * FROM ? WHE... | SQL Iterate Over All Tables | [
"",
"sql",
"sql-server",
"conditional-statements",
"sp-msforeachdb",
""
] |
I am cleaning up a database and there are performance issues with heavy traffic. Reading and writing. But the heavy traffic is condensce to a few days annually.
I suspect one problem is a lot of heavily-used tables don't have a clustered index. But they do have a primary key and a unique, non-clustered index tied to i... | I feel fairly confident in saying that no, this is not a beneficial approach, ever. If a table has only nonclustered indexes, it's a heap table, and aside from bulk insert operations, there is no good reason for having a heap table. That's not just me talking, that's [Microsoft's opinion as well](http://technet.microso... | No. If you have a candidate key, then use it as clustered index. A unique, non-clustered index can be used for key look-ups and to guarantee uniqueness. A clustered index will be used for that, and in addition for range scans and for sort guarantees.
When the heavy traffic is condensed to 'a few days', this is indicat... | Would there ever be a good reason to replace a clustered index with a unique non-clustered index | [
"",
"sql",
"sql-server",
"database-administration",
""
] |
I have a SQL Server table like this:
<http://sqlfiddle.com/#!2/a15dd/1>
What I want to do is display the latest year and month where trades were made.
In this case, i want to display
```
ID: 1
Year: 2013
Month: 11
Trades: 2
```
I've tried to use:
```
select
id, MAX(year), MAX(month)
from
ExampleT... | You can use [ROW\_NUMBER](http://msdn.microsoft.com/en-GB/library/ms186734.aspx) to assign each row a number based on it's relative position (as defined by your order by):
```
SELECT ID,
Year,
Month,
Trades,
RowNum = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Year DESC, Month DESC)
FRO... | Why store "year" and "month" as separate columns? In any case, the basic logic is to combine the two values to get the latest one. This is awkward because you are storing numbers as strings and the months are not zero-padded. But it is not so hard:
```
select id,
max(year + right('00' + month, 2))
from ExampleT... | SQL Server : getting year and month | [
"",
"sql",
"sql-server",
""
] |
I have 3 tables of accounts that all contain the same fields. Table1 contains all accounts while Table2 and Table3 contain subsets of the accounts. I'm trying to select records in Table1 that do no exist in Table2 or Table3.
Let's say the table layout is like this and is the same for all 3 tables:
|AcctNum|Name|State|... | Yes you can combine left joins and with the odd syntax Access uses the query should look like this:
```
SELECT T1.AcctNum
FROM (Table1 AS T1 LEFT JOIN Table2 AS T2 ON T1.AcctNum = T2.AcctNum)
LEFT JOIN Table3 AS T3 ON T1.AcctNum = T3.AcctNum
WHERE (((T2.AcctNum) Is Null) AND ((T3.AcctNum) Is Null));
``` | You can use Access to create a view called **TableCombined** that is a union of both **Table2** and **Table3**.
At that point, you can use your `left join and Is Null` query and join **TableCombined** to **Table1**.
Hope this helps! | How to select records that do not exist in two (or more) tables | [
"",
"sql",
"ms-access-2010",
""
] |
Disclaimer: I'm helping a person learn SQL by using an online tutorial. So you can consider this as a homework question.
There are 3 SQL Server tables that we are dealing with here:
* Ships (name, class)
* Classes - different classes of the ship (class)
* Outcomes - what has happened to that ship (ship, result)
Now ... | With this dataset:
```
with Ships as (
select * from (values
('HMS Prince of Wales','King George V')
,('King George V','King George V')
)Ships(name,class)
),
Classes as (
select * from (values
('King George V')
)Classes(class)
),
Outcomes as (
select * from (values
... | The queries might return different results in many cases. One obvious case is when a sunk ship matches both `class` and `name` in `outcomes`. The `union` in the second query will return one row in this case. The `join` in the first query will return two rows. Hence the counts will be different.
I think you could fix t... | Under what conditions do these two SQL queries give different results? | [
"",
"sql",
"sql-server",
""
] |
I have 3 related tables in the database, the table is A, B & C
table structure as below
table A
```
id | name_A
--- + ---------
1 | Endru
2 | maz
3 | Hudson
```
table B
```
id | name_B
----- + -------
10 | Food
11 | clothes
```
table C
```
id | status
--- + -------
1 | exist
10 | exist
3 | none
```
I ... | I think the following query will fetch what you need
```
SELECT tableC.id, TableA.name_A,TableB.name_B,tableC.status
FROM tableC
LEFT JOIN TableA on TableC.id = TableA .id
LEFT JOIN TableB on TableC.id = TableB .id
``` | You can do this using `union all` and aggregation:
```
select id, max(name_a) as name_a, max(name_b) as name_b,
coalesce(max(status), 'none') as status
from (select id, name_a, NULL as name_b, NULL as status
from tableA
union all
select id, NULL, name_b, NULL
from tableB
union all
... | sql select statement with 3 tables? | [
"",
"mysql",
"sql",
""
] |
Can someone help me put my pl/sql procedure in a package? I've tried and I'm struggling with it:
This is what I have, for my package specification:
```
CREATE OR REPLACE PACKAGE film_pkg
IS
title VARCHAR2(100);
PROCEDURE get_films(fname VARCHAR2);
END film_pkg;
--
```
This is my package body where im running into t... | Your header and body procedure definitions don't match
In the header, you have:
```
PROCEDURE get_films(fname VARCHAR2);
```
Whereas in the body:
```
PROCEDURE get_films(fname IN film.title%type,
r_date OUT film.release_date%type, dur OUT film.duration%type)
```
You probably just need to update the header defi... | "**parameter name** that was inside the procedure defined in the body did not match with the corresponding parameter name in the body." | Oracle Error PLS-00323: subprogram or cursor is declared in a package specification and must be defined in the package body | [
"",
"sql",
"oracle",
"stored-procedures",
"plsql",
"package",
""
] |
i have this query:
```
SELECT distinct
num as number,
name as name
from my_table_name
where number = '12345';
```
And this is the results:
```
number - name
1. 12345 - mike
2. 12345 - charlie
3. 12345 - jose
```
I need a new query when this happens (numbers duplicate or triplicate) show me onl... | Distinct is going to return results that are distinct, relative to all of the data you are querying for. If you only want one of the results returned and you know that the result used is arbitrary, you can just add [a filter based on the row number](http://www.w3schools.com/sql/sql_top.asp) (how specifically this is do... | If you don't care which one is being returned, why are you even asking for it to be returned?
However, to get a single line of results regardless of the number of matching rows, you should probably be using `GROUP BY` and a summary function:
```
Select
num as number,
max(name) as name --or min(), or any other sum... | duplicate values in a row using pl/sql | [
"",
"sql",
"oracle",
""
] |
I am facing one problem in sql queries, Here is the solution i tried:
```
CREATE TABLE #EventTable(eStartDate datetime,eEndDate datetime)
insert into #EventTable VALUES('2014-10-21 10:57:48.603','2014-10-22 10:57:48.603')
insert into #EventTable VALUES('2014-10-23 10:57:48.603','2014-10-23 10:57:48.603')
insert into #... | what I see in you output that you want records of NeedDateTable which have StartDate = EventTable's eEndDate. if this is the case then here is the query :
```
select a.* from NeedDateTable a join EventTable b
on a.StartDate = b.eEndDate;
```
OR if you want to return records of NeedDateTable where exists a record in... | ## Query
```
SELECT a.StartDate,a.EndDate
FROM NeedDateTable a
INNER JOIN
EventTable b
ON a.StartDate=b.eStartDate
OR a.StartDate=b.eEndDate
OR a.EndDate=b.eStartDate
OR a.EndDate=b.eEndDate;
```
## [Fiddle Demo](http://sqlfiddle.com/#!3/6bb04/3) | How to compare dates from one table with another table | [
"",
"sql",
"sql-server",
""
] |
I am trying to get a sql for below data.
I have data like
```
id | flag
1 | Y
2 | Y
1 | Y
2 | N
1 | Y
1 | Y
1 | Y
3 | N
3 | N
3 | N
2 | N
3 | N
```
Expeted output
```
1 | Y
2 | Y
3 | N
```
if id column has Y and or N then display Y. if it contains Only N then Display N | You just need to group and count the values for the group. You said *if it contains Only N then Display N*. This means when all the flags that contain `N` equal all the elements in the group then you should display an `N`. Otherwise, a `Y`.
So you just need to group by and perform the previous comparison. Literally. T... | ```
SELECT [id], MAX([flag])
FROM Table1 GROUP BY [id]
```
[**FIDDLE**](http://sqlfiddle.com/#!6/567af/1) | Assign 'Y' flag if 'Y' is present in multi set table | [
"",
"sql",
""
] |
A school assignment I'm working on says to format a decimal(14,0) column "as currency [US$xxx,xxx] and right justified [all the commas line up vertically]."
I can select the data in the correct format using this:
```
CONCAT("US$", FORMAT(theColumn, 0))
```
But the data is not right justified. I've been searching and... | I think the following query is the answer to your question.
Since the maximum length for a DECIMAL(14,0) type as represented with separators is 18 you have to find out how many spaces you need to add in front of every concatenated result. I calculate the number of digits of number, then the number of commas ((length of... | I think you want
```
select lpad(column_name,x,' ') from table_name;
```
where x is the number of places you want that value you fill (so say 8 places) | How to right-align a column when selecting data? | [
"",
"mysql",
"sql",
""
] |
I have a table that stores pizza orders. The table has a value called quantity; the amount of pizzas in that specific order. I need to "create a query that gets the distribution of orders against different pizza quantities in an order. The questions states"Your sql query should count the number of orders with the follo... | One possible way is using the same `CASE WHEN` statement for the `GROUP BY` clause, for example\* :
```
SELECT CASE
WHEN Quantity <= 6 THEN CAST(Quantity as VARCHAR(1))
ELSE '>6'
END AS Range, COUNT(Quantity) AS Amount
FROM orders
GROUP BY (CASE
WHEN Quantity <= 6 THEN CAST(Quantity as VARCHAR(1))
... | Run this query instead of your previous one:
```
SELECT CASE
WHEN Quantity = 1 THEN '1 '
WHEN Quantity = 2 THEN '2'
WHEN Quantity = 3 THEN '3 '
WHEN quantity = 4 THEN '4'
WHEN quantity = 5 THEN '5 '
WHEN quantity = 6 THEN '6'
ELSE '>6'
END AS Range, COUNT(Quantity) AS Amount
FROM orders
GROUP BY Range
``` | SQL Group By custom range? | [
"",
"sql",
"sql-server",
"select",
"case",
""
] |
We have a piece of software that does not delete entries we no longer want. In order to get a feel for how much data is wasting away in our server and prepare for a big cleanup operation, I am trying to loop through all of the tables and pull the records that are marked for deletion. This is what I'm working with:
```... | Use this system stored procedure
```
sp_MSforeachtable @command1="select count(*) from ?"
```
[sample code](http://weblogs.sqlteam.com/joew/archive/2007/10/23/60383.aspx)
Note:
* This `sp_MSforeachtable` is an undocumented stored procedure.
* Does not support on Azure SQL (per comment below). | Maybe this is what you are looking for
```
DECLARE @NAME VARCHAR(100)
DECLARE @SQL NVARCHAR(300)
DECLARE CUR CURSOR FOR
SELECT NAME
FROM SYS.TABLES
WHERE TYPE = 'U'
AND SCHEMA_ID = 1
OPEN CUR
FETCH NEXT FROM CUR INTO @NAME
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'SELECT * FROM WS_LIVE.D... | How to loop through all SQL tables? | [
"",
"sql",
"sql-server",
"loops",
"t-sql",
""
] |
I have two tables in my datebase:
Cars:
IdCar PK,
Company,
Type,
Color
Renting:
Id-rent\_date PK,
IdCar FK,
Car\_return\_date
I need to write a query that will return three columns:
- Year
- amount of days in which cars of specific company was rented in the year
- Company - from Cars table
For now i have:
> SELECT... | Complete query:
```
declare @iter int
declare @max int
declare @test Table ([Id-rent_date] datetime, Car_return_date datetime, IdCar int)
set @iter = 0
select @max = max(year(Car_return_date) - year([Id-rent_date])) FROM Renting
WHILE(@iter < @max)
BEGIN
... | If you add a `group by` clause, all the items in the select list must either be the columns you've grouped by or aggregate calculations. Here, e.g., you want to sum the amount of days each company had:
```
SELECT SUM(DATEDIFF(dd, Id-rent_date, Car_return_date)) AS Days,
Company
FROM Renting
INN... | Joining two sql tables and grouping | [
"",
"sql",
"group-by",
""
] |
After doing a data migration from an old system, I came across a situation where there are records without dates.


The example I give above is the situation I have. I have nowhere to get the data from those NULL. So what is logi... | I set up a small POC to show you how to do this.
```
CREATE TABLE
#T
(
c1 char(9) NOT NULL
, c2 datetime NULL
);
INSERT INTO
#T
(
c1
, c2
)
VALUES
('0011.001', '2008-12-16T00:00:00.000')
, ('0013.000', NULL)
, ('0013.001', '2008-07-10T00:00:00.000')
, ('0013.002', NULL)
, ('9999.000', ... | First of all: It's good that you move this to a new database. It is a bad design to have range and sub-range in one column.
This should do:
```
update mytable
set mydate =
(
select min(mydate)
from mytable other
where left(other.range,5) = left(mytable.range,5)
)
where mydate is null;
``` | Conditional Upload with Case | [
"",
"sql",
"sql-server",
"ssis",
""
] |
Table by the name Products where column consist of Apple(A) and Grape(G).
```
A G
1 1
1 1
1 Null
```
I ran the Query..
```
Select count(Apple) as 'Apple' count(Grape) as 'Grape'
from products
where Apple = 1 and Grape = 1
```
The Output which i get from the above query is
```
Apple=2
Grape=2
```
Where i sh... | ```
create table AppleGrape(A int, B int)
go
insert into AppleGrape values(1,1)
insert into AppleGrape values(1,1)
insert into AppleGrape values(1,NULL)
SELECT sum(A) as 'Apple',sum(isnull(B,0)) as 'Grape'
FROM AppleGrape
```
check fiddle too. <http://sqlfiddle.com/#!3/126e05/5> | It seems this may be safer if you need a total. It handles null values more safely and doesn't depend on different behaviors from the aggregates default handling of nulls, which can trip some queries up.
```
SELECT SUM(ISNULL(Apple,0)) AS Apple, SUM(ISNULL(Grapes,0)) AS Grape FROM Products
``` | How to Display and Count multiple columns in SQL-2 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I am new to SQL so please bear with me. I am trying to select rows only with specific product codes. When I run it for one selection without OR statement in the below query results are fine but as soon I add another choice with OR statement the results are not accurate. It looks like it keeps putting ProductCode MW-BSh... | Use [IN](http://www.w3schools.com/sql/sql_in.asp) clause and its better to use [Join](http://en.wikipedia.org/wiki/Join_%28SQL%29#Inner_join) instead of [Cartesian product](http://en.wikipedia.org/wiki/Join_%28SQL%29#Cross_join)
```
SELECT Orders.OrderID, OrderDetails.ProductCode
FROM Orders
JOIN OrderDetails
ON Orde... | You can use IN as Srikanth has mentioned. But you need to understand the concept of [operator precedence](http://msdn.microsoft.com/en-us/library/ms190276.aspx) as well. In your case, you are saying "Either Orders.OrderID must equal OrderDetails.OrderID and OrderDetails.ProductCode must equal 'MacFRC', or OrderDetails.... | Select multiple selected values from a column from each row | [
"",
"sql",
""
] |
There's a problem on SQLzoo under More Join operations for MySQL.
The problem asked is
**List the films released in the year 1978 ordered by the number of actors in the cast.**
The tables given are as follows, ord has value of 0 or 1, 1 for star role.
```
movie | actor | casting
id id movieid
yr nam... | You can do the join first, then do the grouping:
```
SELECT movie.*
FROM movie
JOIN casting ON movie.id = casting.movieid
WHERE movie.yr = 1978
GROUP BY movie.id
ORDER BY COUNT(*) DESC
``` | ```
SELECT title, COUNT(actorid) AS actors FROM movie
JOIN casting ON id = movieid
WHERE yr = 1978
GROUP BY title
ORDER BY actors DESC
``` | SQL Join SQLzoo | [
"",
"mysql",
"sql",
"sql-server",
"sqlite",
""
] |
As I doubt my title makes very much sense, I will do my best to explain what I am asking. I need to clean up an audit table which tracks when the state of an object was modified. For one reason or another, multiple records are being created with new dates while the state of the object is still the same. I need to prese... | An alternative solution I finally thought of using LAG() will eliminate the CTE.
```
DELETE @Audits
FROM @Audits a1
INNER JOIN (SELECT ObjectID, DateOfEntry
FROM (SELECT ObjectID, DateOfEntry, ObjectState,
LAG(ObjectState) OVER(PARTITION BY ObjectID ORDER BY DateOfEntry) AS [Pr... | Short answer:
```
; WITH Records AS (
SELECT
ObjectId,
ObjectState,
DateOfEntry,
ROW_NUMBER() OVER (PARTITION BY ObjectID ORDER BY DateOfEntry) AS RowNum
FROM @Audits
)
DELETE R2
FROM Records R1
INNER JOIN Records R2
ON R1.ObjectId = R2.ObjectId
... | Deleting duplicate rows within group ordered by date | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have a table with, for example this data
```
ID |start_date |end_date |amount
---|------------|-----------|-------
a1 |2013-12-01 |2014-03-31 |100
```
Iwant to have a query that split the dates so I have the amount splitted out over the year like this :
```
ID |org_start_date |org_end_date |new_start_date ... | Use `spt_values` table to create a calendar table, then join to your table to split date range into any part you want.
If split by year and divide amount by months you could:
```
with dates as
(
select number,DATEADD(day,number,'20130101') as dt
from master..spt_values
where number between 0 and 1000 AND TYPE... | Here is a solution using a numbers table:
[SQL Fiddle Example](http://sqlfiddle.com/#!3/bb719/10/0)
```
DECLARE @STARTYR INT = (SELECT MIN(YEAR([Start Date])) FROM Table1)
DECLARE @ENDYR INT = (SELECT MAX(YEAR([End Date])) FROM Table1)
SELECT [Id]
, @STARTYR + Number AS [Year]
, CASE WHEN YEAR([Start Date]... | SQL split number over date range | [
"",
"sql",
"sql-server",
"t-sql",
"date-range",
""
] |
I have an Oracle table that looks like below:
```
URL SIZE MODDATE MODTIME
AAA 100 24-OCT-14 10:00:00
AAA 100 24-OCT-14 09:00:00
AAA 100 23-OCT-14 08:00:00
BBB 100 24-OCT-14 10:00:00
BBB 100 24-OCT-14 09:00:00
BBB 100 23-OCT-14 08:00:00
CCC 100 24-OCT-14 10:00:0... | you can use `ROW_NUMBER` analytic function
```
SELECT "URL", "SIZE", "MODDATE", "MODTIME"
FROM
(
SELECT "URL", "SIZE", "MODDATE", "MODTIME",
ROW_NUMBER() OVER ( PARTITION BY "URL" order by "MODDATE" desc, "MODTIME" desc) as seq
FROM Table1
) T
Where T.seq =1
``` | Try:
```
SELECT *
FROM table
WHERE MODDATE IN (SELECT max(MODDATE) FROM table)
ORDER BY MODTIME
``` | Oracle How to select a set of latest entries | [
"",
"sql",
"oracle",
"datetime",
"select",
"unique",
""
] |
So I'm using a node module called json-sql
<https://github.com/2do2go/json-sql>
but the end result is
```
sql.query
// insert into users (name, lastname, age, gender) values ($p1, $p2, 24, $p3);
sql.values
// { p1: 'John', p2: 'Snow', p3: 'male' }
```
Is there a quick way to make that SQL readable? I would like... | Unfortunately the library is unable to natively produce exectuable MS SQL-compliant statements.
A valid MS SQL prepared statement would look like this:
```
sp_EXECUTEsql @statement=N'Select @p as t', @parameters = N'@p varchar(50)', @p=N'Test'
```
So in this case you'd want to do three things:
1. Use the library's ... | It seems that you can use option `separatedValues: false` to get plain sql-query without placeholders.
For example, in your case:
```
var jsonSql = require('json-sql')({separatedValues: false});
sql.query
// insert into "users" ("name", "lastname", "age", "gender") values (\'John\', \'Snow\', 24, \'male\');
```
The... | SQL Statement Doesn't make sense | [
"",
"sql",
"json",
"node.js",
""
] |
i am inserting public holidays for further reference in project, Holiday date is of DATE type and it must be of this type for some reason, i am concatenating @Year with it but it throws error
so how can i just want to put holidays with dynamic year ?
ERROR:
```
Msg 206, Level 16, State 2, Line 3
Operand type clash: i... | I think you need to case year to a varchar like this:
```
CAST(@Year as VARCHAR(4))
```
So that it gets like this:
```
INSERT INTO [dbo].[GazettedHolidays]
Select 1, GETDATE(), 'Kashmir Day', '05 Feb' +CAST(@Year as VARCHAR(4)),'Kashmir Day',1
...
```
And then I think that the YEAR function returns a INT not a DATE... | ```
Declare @Year VARCHAR(10)
Set @Year = (Select Year(Getdate()))
INSERT INTO [dbo].[GazettedHolidays]
Select 1, GETDATE(), 'Kashmir Day', '05 Feb' +@Year,'Kashmir Day',1
Union All
Select 1, GETDATE(), 'Pakistan Day', '23 Mar'+@Year,'Pakistan Day',1
Union All
Select 1, GETDATE(), 'Labour Day', '01 May' +@Year,'Labour ... | How to concatnate only year part in Sql? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have the following table:
```
ID BuyOrSell Total
4 B 10
4 B 11
4 S 13
4 S 29
8 B 20
9 S 23
```
What I am trying to do is to have sum of B and S columns for each ID and if there is not a B or S for an ID have a row with 0, so expected output would be
... | Try this:
```
;WITH CTE(ID, BuyOrSell) AS(
SELECT
ID, T.BuyOrSell
FROM @Temp
CROSS JOIN(
SELECT 'B' UNION ALL SELECT 'S'
)T(BuyOrSell)
GROUP BY ID, T.BuyOrSell
)
SELECT
C.ID,
C.BuyOrSell,
Total = ISNULL(SUM(T.charge), 0)
FROM CTE C
LEFT JOIN @Temp T
ON T.ID = C.ID
... | Here is a solution with tricky join:
```
SELECT t1.ID,
v.l as BuyOrSell,
SUM(CASE WHEN t1.BuyOrSell = v.l THEN t1.charge ELSE 0 END) AS Total
FROM @Temp t1
JOIN (VALUES('B'),('S')) v(l)
ON t1.BuyOrSell = CASE WHEN EXISTS(SELECT * FROM @Temp t2
WHERE t2.ID = t1.I... | SQL - Group by to get sum but also return a row if the sum is 0 | [
"",
"sql",
"sql-server",
"group-by",
"sql-server-2012",
""
] |
I have a table that looks like this:
```
Id | PersonId | Date | Number | NumberOld
------+------------+------------+----------+-----------
1 | 1 | 2014 1 1 | 1 | 0
2 | 1 | 2014 1 2 | 2 | 1
3 | 1 | 2014 1 3 | 3 | ... | You can use LAG to look into the previous record. Thus you find mismatches and with the PersonIDs found you select the persons' histories:
```
select *
from mytable
where personid in
(
select personid
from
(
select personid, numberold, lag(number) over (partition by personid order by logdate, number) as numb... | I think you can do this with a `left join` to find mismatches:
```
select t.person
from table t left join
table tnext
on t.person = tnext.person and t.number = tnext.numberold
where tnext.person is null
group by t.person
having count(*) > 1;
```
The `join` finds all rows where the numbers don't match. Howev... | TSQL - Query to verify continuity | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I dont think a count will work here, can someone help me get an sql that identifies which account numbers have multiple agents, more than two agents in the where condition.
```
AGENT_NAME ACCOUNT_NUMBER
Clemons, Tony 123
Cipollo, Michael 123
Jepsen, Sarah 567
Joanos, James ... | You can do this using window functions:
```
select t.account_number, t.agent_name
from (select t.*, min(agent_name) over (partition by account_number) as minan,
max(agent_name) over (partition by account_number) as maxan
from table t
) t
where minan <> maxan;
```
If you know the agent names ar... | Using count function u can get the result
```
CREATE TABLE #TEMP
(
AGENT_NAME VARCHAR(100),
ACCOUNT_NUMBER INT
)
INSERT INTO #TEMP
VALUES ('CLEMONS, TONY',123),
('CIPOLLO, MICHAEL',123),
('JEPSEN, SARAH',567),
('JOANOS, JAMES',567),
('MCMAHON, BRI... | sql that identifies which account numbers have multiple agents | [
"",
"sql",
"sql-server",
""
] |
I have an auto-generated SQL script to run on 5.6.17-157.2.
It worked fine on 5.5.33-1.17.1.
Every SQL statement shows `\g` at the end. For example
```
CREATE TABLE articoli
(
ID INT,
titolo LONG... | MySQL already does accept `\g`, but it must follow a SQL statement.
The `\g` is basically the same as `;` That is, it is the terminator for a statement and that means send it to the server for parsing and execution.
Your sample shows a create table statement terminated by *both* a semicolon and `\g`. This results in ... | <http://dev.mysql.com/doc/refman/5.1/en/mysql-commands.html>
> go - (\g) - Send command to mysql server. | What does `\g` mean at the end of a MySQL statement? And how do I fix queries not running? | [
"",
"sql",
"mysql",
"database",
"mysqlcommand",
"mysql-command-line-client",
""
] |
I'm running contests on my website. Every contest could have multiple entries. I want to retrieve the best 3 entries or more (in the case of draw) based on the score. The score is calculated as the sum of the score of all votes.
Here is the SQLFiddle: <http://sqlfiddle.com/#!9/c2480>
The table ENTRY is as follows:
`... | Here are the SQLFiddle link: <http://sqlfiddle.com/#!9/c2480/50/0>
I managed to solve the query by using joins instead of subquery.
The query i posted on the question are getting error because the second subquery was finishing with ";":
```
select distinct(final_score) from (
select entry_id, sum(score) as final_... | ```
SELECT entry_id,total
FROM
( SELECT x.*
, IF(@prev=total,@i,@i:=@i+1) i,@prev:=total prev
FROM
( SELECT entry_id
, SUM(score) total
FROM entry_vote
GROUP
BY entry_id
) x
... | Mysql query for winners in the contest including draws entries having score in another table | [
"",
"mysql",
"sql",
""
] |
Need to find columns that match the following condition.
* Must start with "Foo"
* Follow by a number of any length
* Follow by a space or "-"
* Follow by a number of any length
* End or follow by A,B,C, PE, a period, or a space
So the following would match
* Foo42004 45058
* Foo42004-45058
* Foo42004 45058A
* Foo42... | TSQL has no notion of the {0,15} like in Regex. So the part of your pattern Foo[0-9]{0,15} would match the strings Foo0{0,15}, Foo1{0,15}, Foo2{0,15}, ... Foo9{0,15} etc. Like BlorgBeard said, LIKE is limited. | The fastest way to implement this would be to use a CLR to implement a real regular expression function. There are many free options available with a google search for "sql clr regex" as well as instructions on how to roll your own.
Your other option would be to build your own function, using T-SQL [string parsing fun... | TSQL pattern matching with like | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am receiving this error when trying to execute the query below. Any ideas or suggestions?
Error:
> Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in ... | The problem is here you can't combine an outer and inner reference in an aggregate function
```
(SELECT TOP 100 PERCENT SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
WHEN C... | I'd recommend commenting out `bandComponents` then `cutScores`, rerunning after removing each components and seeing where the query fails. Once you figure out where it's failing, then you can fix it.
Also, could be this line, the query in your Percent column.
```
ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPo... | Error: "Multiple columns are specified in an aggregated expression containing an outer reference." | [
"",
"sql",
"sql-server",
"t-sql",
"aggregation",
""
] |
I normally work with Ruby on Rails and write most of my DB queries via the Ruby adapter interface.
This time, however, I'm actually creating a DB view and need to write the SQL itself so that this view can be queried (working with a Legacy system).
I've tried to make these examples simpler than the system yet still s... | You could try an Outer Apply, something like below
```
select * from parent par
outer apply
( select top 1 * from children child
outer apply
( select top 1 * from pets left join pet_types where child.id=pets.child_id
order by created_at desc) pet
where par.id=child.parent_id
... | Try this:
```
SELECT
t0.ParentName,
t0.ChildName,
t0.PetName,
t0.PetValue
FROM
(SELECT
t1.name as ParentName,
t2.name as ChildName,
t3.name as PetName,
t4.value as PetTypeValue,
MAX(t2.created_at) as MaxDateChild,
MAX(t3.created_at) as MaxDatePet
FROM
... | MS SQL Server: complex JOIN query among several tables | [
"",
"sql",
"sql-server",
"join",
""
] |
I am trying to define a database schema to store a list of "objects" in a table.
The main problem is that I need to have a list of geometric shapes and other kinds of markers in a table, in order to draw them on to a google map.
For example, a circle will have only x,y and radius. A polyline will have a set of points... | You'll have to pack the data in some format, store it, and unpack it later for use. For example, JSON, which is supported by both PHP and JS. For example in PHP:
```
$shape = array("kind"=>"circle", "cx"=>45,"cy"=>90,"r"=>20);
$json = json_encode($shape, JSON_NUMERIC_CHECK); // NUMERIC_CHECK doesn't treat numbers as s... | I 'd suggest to have a look at the [spatial extensions for MySQL](http://dev.mysql.com/doc/refman/5.0/en/spatial-extensions.html) and
[POSTGIS](http://postgis.net/) extension for postgresql which both support storing multiple types of geometry in a spatial columns. | SQL Store different types of objects in a single table | [
"",
"mysql",
"sql",
""
] |
I have an oracle database table with a lot of columns. I'd like to count the number of fully unique rows. The only thing I could find is:
```
SELECT COUNT(DISTINCT col_name) FROM table;
```
This however would require me listing all the columns and I haven't been able to come up with syntax that will do that for me. I... | How about
```
SELECT COUNT(*)
FROM (SELECT DISTINCT * FROM Table)
``` | It depends on what you are trying to accomplish.
To get a count of the distinct rows by specific column, so that you know what data exists, and how many of that distinct data there are:
```
SELECT DISTINCT
A_CODE, COUNT(*)
FROM MY_ARCHV
GROUP BY A_CODE
```
--This informs me there are 93 unique codes, and how man... | How to count unique rows in Oracle | [
"",
"sql",
"oracle",
""
] |
I am running following sql.
```
SELECT value FROM ppr_price_factor WHERE product_factor_id=3;
```
which returns values like this
```
17
25
35
45
```
I need to display my results as something like below.
```
value value Range
17 0-17
25 18-25
35 26-35
45 36-45
```
Can I do thi... | Maybe that helps:
```
SELECT value,
TO_CHAR(1 + LAG(value, 1, -1) OVER (ORDER by value)) || '-' || TO_CHAR(value) AS value_range
FROM your_table
``` | I would use [case](http://dev.mysql.com/doc/refman/5.0/en/case.html) statement for the respective problem.
You can use the following sql as a reference
```
SELECT value
,CASE
WHEN value >= 0
AND value <= 17
THEN '0-17'
WHEN value >= 18
AND value <= 25
... | break into ranges using sql | [
"",
"sql",
"oracle",
""
] |
I have a table with the following columns in a MySQL database.
```
Chapters
Columns:
id int(11) AI PK
title varchar(100)
text varchar(10000)
created datetime
revision int(11)
book_id int(11)
```
Each book (book\_id) can have multiple chapters. Each chapter can have multiple revis... | Because it's mysql, you can do it thus;
```
select * from (
select * from chapters
order by revision desc) x
group by book_id, title
```
This non-standard grouping functionality is a mysql-only trick, and although the documentation says the actual row you get for each group is non deterministic in reality it ... | Something like this should work. Effectively we are grabbing the top 1 result from the data ordered by the criteria you mentioned.
```
select id, title, text, created, revision
from chapters
order by id desc, created asc, revision desc
limit 1
``` | Need to get most recent chapter within book | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
I recently came across few decode queries.
I found this decode function somewhat confusing. here are the queries:
```
SELECT promo_id,
DECODE(NVL(promo_cost,0),promo_cost, promo_cost * 0.25, 100) "Discount"
FROM promotions;
SELECT promo_id,
DECODE(promo_cost,10000, DECODE(promo_category, 'G1', promo_c... | The syntax for `DECODE` function is `DECODE( expression , search , result [, search , result]... [, default] )`.
In your first query :
`DECODE(NVL(promo_cost,0),promo_cost, promo_cost * 0.25, 100)`
The following is the interpretation :
```
expression = NVL(promo_cost,0)
search = promo_cost
result = promo_co... | ```
DECODE(NVL(promo_cost,0),promo_cost, promo_cost * 0.25, 100) "Discount"
```
= CASE WHEN NVL(promo\_cost,0) = promo\_cost THEN promo\_cost \* 0.25 ELSE 100 END
```
DECODE(promo_cost,10000, DECODE(promo_category, 'G1', promo_cost *.25, NULL), NULL)
```
= CASE WHEN promo\_cost = 10000 THEN DECODE(promo\_category, '... | DECODE Oracle SQL | [
"",
"sql",
"oracle",
"decode",
""
] |
I have to concatenate two fields and use concatenated field in where clause but it gives me invalid identifier. How to solve this query.
```
select i.FIRST_NAME || ' - ' || i.LAST_NAME as NAME, i.* from CONTACT i
where NAME = 'JOHN - HANKS'
```
This gives me
```
ORA-00904: "NAME": invalid identifier
00904. 00000 - ... | You cannot use a column alias at the same level. Just use a subquery (or repeat the expression):
```
select c.*
from (select i.FIRST_NAME || ' - ' || i.LAST_NAME as NAME, i.*
from CONTACT i
) c
where c.NAME = 'JOHN - HANKS';
``` | The WITH clause is also a good alternative, better readability. Also, if the subquery is to be used multiple times, it is even better.
```
WITH data as(
select i.FIRST_NAME || ' - ' || i.LAST_NAME as NAME, i.* from CONTACT i)
select * from data where name = 'JOHN - HANKS';
``` | Concatenate and use in where clause oracle plsql | [
"",
"sql",
"oracle",
""
] |
If I'll execute below query then I'm getting more than 1000 records here
```
select
ID, name, 'Default value' as "Other"
from
emp_table
```
Output:
```
ID | Name | Other
---------------------------------
1 | H | Default value
2 | V | Default value
3 | D | Default ... | If you are using SQL Server you can use ROW\_NUMBER() to add a row number to the query and then use a `CASE` statement to write the default value or null:
```
select
ID,
NAME,
CASE ROW_NUMBER() OVER(ORDER by NAME)
WHEN 1 THEN 'Default Value'
ELSE NULL
END AS [Other]
from emp_tabl... | ```
SELECT ID,
name,
CASE
WHEN ID=1 THEN 'Default value'
ELSE NULL
END AS "Other"
FROM emp_table
``` | Build SQL Query with Customized Virtual Values | [
"",
"sql",
""
] |
I am working in SQL. What is the complete explanation for using comments in SQL, with some example code? | MySQL Server supports three comment styles:
From a `#` character to the end of the line.
From a `--` sequence to the end of the line. In MySQL, the “-- ” (double-dash) comment style requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on). This... | **In Oracle, there are three ways.**
**1.**
```
SQL> REM This is a comment
```
**2.**
```
SQL> -- This is a single line comment
```
**3.**
```
SQL> /* This is a
SQL> multiple line
SQL> comment */
SQL>
```
The difference between REM and the other two is that, -- and /\* \*/ can be used in a `PL/SQL` block, while ... | How to give comments in SQL | [
"",
"mysql",
"sql",
"oracle",
""
] |
Let's say I have a table like this
```
CREATE TABLE events (
id INT,
sensor INT,
event_type INT,
time datetime
);
INSERT INTO events VALUES (0,2,4,'2012-06-08 12:13:14');
INSERT INTO events VALUES (1,3,4,'2012-06-08 13:13:14');
INSERT INTO events VALUES (2,2,4,'2012-06-08 12:15:14');
INSERT INTO events VALU... | This one variant using `GROUP BY`, need to run with your data and see the performance
```
SELECT events.id, events.sensor
FROM events
JOIN
(
SELECT sensor, max(time) as maxTime
FROM events
group by sensor
) T
on events.sensor = T.sensor
and events.time = T.maxTime
ORDER BY events.time DESC
``` | ```
select * from events
where time in(SELECT max(time) FROM events
group by sensor_id,event_type)
Order by time desc;
``` | SQL how to select the most recent timestamp by values? | [
"",
"mysql",
"sql",
"group-by",
"timestamp",
""
] |
I'am currently developing a program and i want to write a function which is accept a value in following format
```
"AAAA BBBB" CCCC DDDD EEEE "FFFF GGGG HHHH"
```
I want to replace the spaces in above with "\_" and need a output as showed following format (please note that this should happen only for string which is... | Please refer this code.
I think this code will give some hint.
This code is not the tested code. I am posting answer Because at least you get some hint to find your solution.
```
DECLARE @In VARCHAR(50) = '"AAAA BBBB" CCCC DDDD EEEE "FFFF GGGG HHHH IIIII'
DECLARE @Quote SMALLINT = -1, @Index INT = 1, @Char CHAR(1) ,... | Here are the modifications I would make
* Once all replacements have been made, exit existing the loop (added WHILE loop condition and how logic for the quote recognition behaves to facilitate the exit)
* Remove dependencies on any length (CHAR(100), SUBSTRING(...,213))
**Code**
```
DECLARE @In VARCHAR(50) = '"AAAA ... | SQL Character Replace function extend | [
"",
"sql",
"sql-server",
"replace",
"sql-function",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.