How to select rows with no matching entry in another table?
I would use EXISTS
expression since it is more powerful, you can e.g. more precisely choose rows you would like to join. In the case of LEFT JOIN
, you have to take everything that's in the joined table. Its efficiency is probably the same as in the case of LEFT JOIN
with null constraint.
SELECT t1.ID
FROM Table1 t1
WHERE NOT EXISTS (SELECT t2.ID FROM Table2 t2 WHERE t1.ID = t2.ID)
SELECT id FROM table1 WHERE foreign_key_id_column NOT IN (SELECT id FROM table2)
Table 1 has a column that you want to add the foreign key constraint to, but the values in the foreign_key_id_column
don't all match up with an id
in table 2.
- The initial select lists the
id
s from table1. These will be the rows we want to delete. - The
NOT IN
clause in the where statement limits the query to only rows where the value in theforeign_key_id_column
is not in the list of table 2id
s. - The
SELECT
statement in parenthesis will get a list of all theid
s that are in table 2.
Here's a simple query:
SELECT t1.ID
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL
The key points are:
LEFT JOIN
is used; this will return ALL rows fromTable1
, regardless of whether or not there is a matching row inTable2
.The
WHERE t2.ID IS NULL
clause; this will restrict the results returned to only those rows where the ID returned fromTable2
is null - in other words there is NO record inTable2
for that particular ID fromTable1
.Table2.ID
will be returned as NULL for all records fromTable1
where the ID is not matched inTable2
.