patternsqlMinor
Listing Non-Record
Viewed 0 times
listingrecordnon
Problem
I have two tables.
1st table:
called kimlik
2nd table:
called siparis
I want to list via SQL query to persons who doesn't give an order on 22.09.2011.
Result:
1st table:
called kimlik
id ad
---------------
1 ahmet
2 mehmet
3 ali2nd table:
called siparis
id kimlikid tarih miktar
------------------------------------------------------------
1 1 22.09.2011 10
1 2 22.09.2011 100I want to list via SQL query to persons who doesn't give an order on 22.09.2011.
Result:
ad tarih
--------------------------
ali 22.09.2011Solution
Some methods:
NOT IN
NOT EXISTS
LEFT JOIN
The method you choose is usually down to personal preference and performance (they can produce different query plans depending on your data volumes), ie: NOT EXISTS is frequently faster than LEFT JOIN if siparis has 1,000s of rows per kimlik id.
EDIT: Added on variable to compare and display in result set
NOT IN
DECLARE @NoDateWanted date = '22.09.2011';
SELECT ad, @NoDateWanted as tarih
FROM
kimlik k
WHERE
k.ID NOT IN (SELECT kimlikid FROM siparis s WHERE s.tarih = @NoDateWanted)NOT EXISTS
DECLARE @NoDateWanted date = '22.09.2011';
SELECT ad, @NoDateWanted as tarih
FROM
kimlik k
WHERE
NOT EXISTS(SELECT 'kimlik' FROM siparis s
WHERE k.id = s.kimlikid
and s.tarih = @NoDateWanted)LEFT JOIN
DECLARE @NoDateWanted date = '22.09.2011';
SELECT ad, @NoDateWanted as tarih
FROM
kimlik k
left join siparis s
on s.kimlikid = k.id
and s.tarih = @NoDateWanted
WHERE s.id IS NULLThe method you choose is usually down to personal preference and performance (they can produce different query plans depending on your data volumes), ie: NOT EXISTS is frequently faster than LEFT JOIN if siparis has 1,000s of rows per kimlik id.
EDIT: Added on variable to compare and display in result set
Code Snippets
DECLARE @NoDateWanted date = '22.09.2011';
SELECT ad, @NoDateWanted as tarih
FROM
kimlik k
WHERE
k.ID NOT IN (SELECT kimlikid FROM siparis s WHERE s.tarih = @NoDateWanted)DECLARE @NoDateWanted date = '22.09.2011';
SELECT ad, @NoDateWanted as tarih
FROM
kimlik k
WHERE
NOT EXISTS(SELECT 'kimlik' FROM siparis s
WHERE k.id = s.kimlikid
and s.tarih = @NoDateWanted)DECLARE @NoDateWanted date = '22.09.2011';
SELECT ad, @NoDateWanted as tarih
FROM
kimlik k
left join siparis s
on s.kimlikid = k.id
and s.tarih = @NoDateWanted
WHERE s.id IS NULLContext
StackExchange Database Administrators Q#6474, answer score: 5
Revisions (0)
No revisions yet.