SQL
Find Records Present in One Table But Missing in Another
Efficiently identify and retrieve rows that exist in a primary table but have no corresponding match in a secondary table using a LEFT JOIN and NULL check.
SELECT
A.*
FROM
TableA AS A
LEFT JOIN
TableB AS B ON A.id = B.id
WHERE
B.id IS NULL;
-- Alternative using NOT EXISTS
-- SELECT
-- A.*
-- FROM
-- TableA AS A
-- WHERE
-- NOT EXISTS (SELECT 1 FROM TableB AS B WHERE A.id = B.id);
How it works: This snippet demonstrates how to find records that exist in `TableA` but do not have a matching record in `TableB`. It uses a `LEFT JOIN` to combine rows from `TableA` with matching rows from `TableB`. If no match is found in `TableB`, the columns from `TableB` will be `NULL`. The `WHERE B.id IS NULL` clause then filters for precisely these unmatched records. An alternative and often performant method using `NOT EXISTS` is also provided.