QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › JOIN

How do you find records that have no match in another table?

An anti-join returns the rows of the left table that have no pair in the right one. It is written as a LEFT JOIN with the right key IS NULL, or as NOT EXISTS. NOT IN with a subquery is avoided: a single NULL in it makes the query return 0 rows, hiding the defect. A LEFT JOIN checks a column that cannot be NULL, ideally the primary key.

SQL · JOIN

After sign-up some users have no account or order. How do you find all of them in one query?

One of the most useful integrity checks is the search for "orphans": users without orders, orders without a payment, transactions without a log entry. The technique is called an anti-join. It can be written three ways, and one of them silently returns 0 rows exactly when the data has a defect. This lesson shows all three, explains why NOT IN lets you down and gives a rule of choice.

How it works and why. An anti-join returns the rows of the left table that have no pair on the right. There are two safe ways to write it. The first: LEFT JOIN and selecting rows where the right table's key IS NULL. LEFT JOIN keeps a row without a pair with NULLs in the right columns, and we keep exactly those. The second: NOT EXISTS with a subquery that checks for a pair. Both give the same result, and modern optimisers (PostgreSQL, MySQL 8.0.17+) plan them as an anti-join without multiplying rows.

The third way, NOT IN (SELECT …), reads the simplest but has a three-valued logic trap. x NOT IN (1, 2, NULL) expands to "x is not 1 AND not 2 AND not NULL". The last comparison gives UNKNOWN, so the whole expression never becomes true: at best UNKNOWN, and WHERE takes only true.

Example: an empty result that looks like "all is well". Users: Anna (1), Ivan (2), Olha (3). Orders: 100 and 101 belong to Anna, 102 to Ivan, 103 is a guest order with user_id = NULL. Someone writes:

SELECT id, email
FROM users
WHERE id NOT IN (SELECT user_id FROM orders);
-- 0 rows, although Olha has no orders

The query returns 0 rows. The conclusion "everyone has an order" would be a mistake: the subquery contains a NULL (the guest order), and for Olha the expression 3 NOT IN (1, 1, 2, NULL) is UNKNOWN. A test for "no orphans" passes and the defect stays. The fix:

-- NOT EXISTS: safe with NULL
SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.user_id = u.id
);

-- LEFT JOIN + IS NULL: the same, test the right table key
SELECT u.id, u.email
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.id IS NULL;

Both queries return Olha. The fact that a NULL exists in orders.user_id is a finding too, but a different one: it is a guest order and should be asked about separately (WHERE user_id IS NULL).

Why NOT IN returns nobody

id NOT IN (1, 1, 2, NULL)
userresult
1 AnnaFALSE
2 IvanFALSE
3 OlhaUNKNOWN filtered
NOT EXISTS
userresult
3 OlhaTRUE
Figure 1. For Olha, NOT IN gives UNKNOWN because of the NULL in the list, and the row is dropped. NOT EXISTS finds her.

Which way to choose

NOT EXISTSNULLs in the data do not affect the resultLEFT JOIN … IS NULLtest a NOT NULL column of the right tableNOT IN (subquery)one NULL in the subquery and you get 0 rows
Figure 2. NOT EXISTS and LEFT JOIN … IS NULL are safe. NOT IN is safe only when the subquery is guaranteed to have no NULL.

Limits and alternatives. For an anti-join with LEFT JOIN, test a column that cannot be NULL in a real row, best of all the right table's primary key. If you test a nullable column (o.total IS NULL), real orders with an empty amount land in the result, which are false "orphans". A condition on the right table that is not part of the link goes in ON (for example "users without an active account": ON a.user_id = u.id AND a.status = 'active'), while IS NULL stays in WHERE; a separate lesson covers this. There is also EXCEPT: SELECT id FROM users EXCEPT SELECT user_id FROM orders returns only keys, not full rows, and treats NULLs as equal values. An anti-join on a composite key requires comparing all columns in NOT EXISTS or ON. On large tables speed depends on an index on the link column in the right table, and the anti-join result is usually small, so it is convenient to add as a check in automated tests: 0 rows are expected.

Common mistakes.

  • NOT IN with a subquery where NULL is possible: 0 rows, and the check wrongly "passes".
  • IS NULL on a column that allows NULL: the result has "orphans" that are not there.
  • Putting the right table's status condition in WHERE: the search turns into plain filtering.
  • Looking for "orphans" through INNER JOIN: such rows disappear from it by definition.
  • Not looking separately at NULL in the foreign key: guest or broken records stay out of sight.

Check yourself

SELECT * FROM users WHERE id NOT IN (SELECT user_id FROM orders) returned 0 rows, although SELECT COUNT(*) FROM users shows 3 users and one of them never bought anything. Name the most likely cause and the check.

Answer

orders.user_id contains NULL (a guest or broken order), and NOT IN returns nothing because of UNKNOWN. The check: SELECT COUNT(*) FROM orders WHERE user_id IS NULL. The fix: NOT EXISTS or LEFT JOIN … IS NULL.

To find users with no active account, someone writes LEFT JOIN accounts a ON a.user_id = u.id WHERE a.status IS NULL. Why is this query wrong?

Answer

It does not check for active. A user with only a closed account has status = closed, not NULL, and will not be in the result, while an account with an empty status gives a false match. The right way: move the active condition into ON (ON a.user_id = u.id AND a.status = 'active') and test the key in WHERE: WHERE a.id IS NULL.

In an interview. Junior: I find records without a pair with a LEFT JOIN and the condition that the right table's key IS NULL, or with NOT EXISTS. It is one of my main queries for integrity checks: for example users without an account or transactions without a log entry. Middle/Senior: I avoid NOT IN with a subquery: one NULL turns the result empty and hides the defect. For LEFT JOIN I test a column that cannot be NULL (the right table's primary key) and put pair conditions in ON. I add such queries to automated tests with 0 rows expected.

More articles in this chapter