How to exclude rows that do not join with another table?

I have two tables, one has a primary key, the other as a foreign key.

I want to extract data from the primary table only if there is no record in the secondary table containing its key. The opposite kind of simple inner join, which returns only the rows that are joined by this key.

+64
sql join
Dec 30 '10 at 6:21
source share
8 answers

alt text

SELECT <select_list> FROM Table_A A LEFT JOIN Table_B B ON A.Key = B.Key WHERE B.Key IS NULL 

Full image of joining alt text

From Atom: http://www.codeproject.com/KB/database/Visual_SQL_Joins.aspx

+221
Dec 30 '10 at 6:48
source share
 SELECT * FROM primarytable P WHERE NOT EXISTS (SELECT * FROM secondarytable S WHERE P.PKCol = S.FKCol) 

As a rule, (NOT) EXISTS is the best choice, then (NOT) IN or (LEFT) JOIN

+7
Dec 30 '10 at 6:23
source share

use the "does not exist" left join:

 SELECT p.* FROM primary_table p LEFT JOIN second s ON p.ID = s.ID WHERE s.ID IS NULL 
+4
Dec 30 '10 at 6:24
source share
 SELECT P.* FROM primary_table P LEFT JOIN secondary_table S on P.id = S.p_id WHERE S.p_id IS NULL 
+3
Dec 30 '10 at 6:25
source share

If you want to select the columns from the first table, which are also present in the second table, then in this case you can also use EXCEPT . In this case, the column names may be different, but the data type should be the same.

Example:

 select ID, FName from FirstTable EXCEPT select ID, SName from SecondTable 
+2
Dec 30
source share

Another solution:

 SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2) 
+1
Nov 01 '18 at 7:15
source share

It was useful to use it in COGNOS because the creation of the SQL query "Not in" in Cognos was allowed, but it took too much time to start. I had a manually encoded table A to join table B in Cognos, since A.key was not in B.key, but the query took too long or did not return results after 5 minutes.

For anyone looking for a β€œNOT IN IN” solution in Cognos, here's what I did. Create a query that joins tables A and B with LEFT JOIN in Cognos, choosing the type of link: table A.Key has values ​​from 0 to N in table B and then adds a filter (they correspond to Where Clauses) for: table B.Key - NULL

Quick and fast, like a charm.

0
Jul 10 '17 at 18:17
source share

I have another call. What if I want to exclude rows that are not joined with two other tables

0
Jun 12 '19 at 14:24
source share