Joining Tables · Lesson 28 of 64

SQL Finding Missing Rows

What you will learn

  • How to find rows with no match using LEFT JOIN ... IS NULL
  • How NOT EXISTS does the same job
  • Why NOT IN can be a trap
  • How to check the answer

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. The question

"Which ... have no ...?" is a common question: customers without orders, products never sold, courses nobody teaches. The rows you want are the ones that are missing from another table. The tool is called an anti-join. In this lesson the question is:

Which customers have never placed an order?

Which customers have no account?

Which courses have no section?

2. LEFT JOIN and IS NULL

Do a LEFT JOIN from the parent to the child (lesson 4.3). Parents with no child have NULL in the child's columns. Keep exactly those rows by testing a child column that can never be NULL for a real match, such as its primary key:

SELECT p.customer_id, p.first_name, p.last_name
FROM customers AS p
LEFT JOIN orders AS c ON c.customer_id = p.customer_id
WHERE c.order_id IS NULL
ORDER BY p.customer_id LIMIT 8;
customer_id  first_name  last_name
-----------  ----------  ---------
         14  Leo         Khan
         19  Dana        Sato
         22  Jin         Lopez
         23  Bruno       Wang
         25  Tariq       Uddin
         29  Wei         Kamau
         38  Ibrahim     Kamau
         40  Quinn       Wang
(8 rows)
SELECT p.customer_id, p.full_name, p.city
FROM customers AS p
LEFT JOIN accounts AS c ON c.customer_id = p.customer_id
WHERE c.account_id IS NULL
ORDER BY p.customer_id LIMIT 8;
customer_id  full_name    city
-----------  -----------  ------------
          2  Rafi Uddin   Manila
          4  Mei Bianchi  Osaka
          6  Farid Park   Austin
         14  Leo Rahman   Porto Alegre
         18  Ines Cohen   Lima
         21  Sven Varga   Dhaka
         30  Farid Varga  Leeds
         38  Gita Khan    Lima
(8 rows)
SELECT p.course_id, p.code, p.title
FROM courses AS p
LEFT JOIN sections AS c ON c.course_id = p.course_id
WHERE c.section_id IS NULL
ORDER BY p.course_id LIMIT 8;
course_id  code   title
---------  -----  ----------------
       17  CS101  Computing Basics
(1 row)

(Remember lesson 2.5: the test is IS NULL, not = NULL.) This is the LEFT JOIN ... IS NULL pattern, and it is the one to remember. Read it as: "all parents, joined to their children, but keep only the rows where no child was found."

3. NOT EXISTS

NOT EXISTS asks the same question with a subquery (a query inside brackets, chapter 7): "keep the parent if there is no child row with its key":

SELECT p.customer_id, p.first_name, p.last_name
FROM customers AS p
WHERE NOT EXISTS (SELECT 1 FROM orders AS c WHERE c.customer_id = p.customer_id)
ORDER BY p.customer_id LIMIT 8;
customer_id  first_name  last_name
-----------  ----------  ---------
         14  Leo         Khan
         19  Dana        Sato
         22  Jin         Lopez
         23  Bruno       Wang
         25  Tariq       Uddin
         29  Wei         Kamau
         38  Ibrahim     Kamau
         40  Quinn       Wang
(8 rows)
SELECT p.customer_id, p.full_name, p.city
FROM customers AS p
WHERE NOT EXISTS (SELECT 1 FROM accounts AS c WHERE c.customer_id = p.customer_id)
ORDER BY p.customer_id LIMIT 8;
customer_id  full_name    city
-----------  -----------  ------------
          2  Rafi Uddin   Manila
          4  Mei Bianchi  Osaka
          6  Farid Park   Austin
         14  Leo Rahman   Porto Alegre
         18  Ines Cohen   Lima
         21  Sven Varga   Dhaka
         30  Farid Varga  Leeds
         38  Gita Khan    Lima
(8 rows)
SELECT p.course_id, p.code, p.title
FROM courses AS p
WHERE NOT EXISTS (SELECT 1 FROM sections AS c WHERE c.course_id = p.course_id)
ORDER BY p.course_id LIMIT 8;
course_id  code   title
---------  -----  ----------------
       17  CS101  Computing Basics
(1 row)

The result is the same. Many people find NOT EXISTS easier to read ("there is no ..."), and many databases optimise it well. Choose the one you understand best.

4. NOT IN and its trap

NOT IN with a list of the child's keys also works, as long as that list contains no NULL (lesson 2.3):

SELECT p.customer_id, p.first_name, p.last_name
FROM customers AS p
WHERE p.customer_id NOT IN (SELECT customer_id FROM orders)
ORDER BY p.customer_id LIMIT 8;
customer_id  first_name  last_name
-----------  ----------  ---------
         14  Leo         Khan
         19  Dana        Sato
         22  Jin         Lopez
         23  Bruno       Wang
         25  Tariq       Uddin
         29  Wei         Kamau
         38  Ibrahim     Kamau
         40  Quinn       Wang
(8 rows)
SELECT p.customer_id, p.full_name, p.city
FROM customers AS p
WHERE p.customer_id NOT IN (SELECT customer_id FROM accounts)
ORDER BY p.customer_id LIMIT 8;
customer_id  full_name    city
-----------  -----------  ------------
          2  Rafi Uddin   Manila
          4  Mei Bianchi  Osaka
          6  Farid Park   Austin
         14  Leo Rahman   Porto Alegre
         18  Ines Cohen   Lima
         21  Sven Varga   Dhaka
         30  Farid Varga  Leeds
         38  Gita Khan    Lima
(8 rows)
SELECT p.course_id, p.code, p.title
FROM courses AS p
WHERE p.course_id NOT IN (SELECT course_id FROM sections)
ORDER BY p.course_id LIMIT 8;
course_id  code   title
---------  -----  ----------------
       17  CS101  Computing Basics
(1 row)

It works here because the key column of the child has no NULL. If it ever did, the whole query would return nothing. A foreign key column that allows NULL (an optional link) is exactly where this goes wrong. NOT EXISTS and LEFT JOIN ... IS NULL do not have this problem, so prefer them.

5. Check the answer

The parents with no child plus the parents with a child must equal all parents. Verify it:

SELECT (SELECT COUNT(*) FROM customers) AS all_parents,
       (SELECT COUNT(*) FROM customers AS p WHERE EXISTS (SELECT 1 FROM orders AS c WHERE c.customer_id = p.customer_id)) AS with_children,
       (SELECT COUNT(*) FROM customers AS p WHERE NOT EXISTS (SELECT 1 FROM orders AS c WHERE c.customer_id = p.customer_id)) AS without_children;
all_parents  with_children  without_children
-----------  -------------  ----------------
        420            365                55
(1 row)
SELECT (SELECT COUNT(*) FROM customers) AS all_parents,
       (SELECT COUNT(*) FROM customers AS p WHERE EXISTS (SELECT 1 FROM accounts AS c WHERE c.customer_id = p.customer_id)) AS with_children,
       (SELECT COUNT(*) FROM customers AS p WHERE NOT EXISTS (SELECT 1 FROM accounts AS c WHERE c.customer_id = p.customer_id)) AS without_children;
all_parents  with_children  without_children
-----------  -------------  ----------------
        300            236                64
(1 row)
SELECT (SELECT COUNT(*) FROM courses) AS all_parents,
       (SELECT COUNT(*) FROM courses AS p WHERE EXISTS (SELECT 1 FROM sections AS c WHERE c.course_id = p.course_id)) AS with_children,
       (SELECT COUNT(*) FROM courses AS p WHERE NOT EXISTS (SELECT 1 FROM sections AS c WHERE c.course_id = p.course_id)) AS without_children;
all_parents  with_children  without_children
-----------  -------------  ----------------
         19             18                 1
(1 row)

The last two add up to the first. A check like this takes seconds and catches many mistakes.

6. The other direction

To find child rows whose parent is missing (an "orphan"), swap the roles. In a database with foreign keys switched on there should be none, which is itself a useful check:

SELECT c.order_id, c.customer_id
FROM orders AS c
LEFT JOIN customers AS p ON p.customer_id = c.customer_id
WHERE p.customer_id IS NULL;
order_id  customer_id
--------  -----------
(0 rows)
SELECT c.account_id, c.customer_id
FROM accounts AS c
LEFT JOIN customers AS p ON p.customer_id = c.customer_id
WHERE p.customer_id IS NULL;
account_id  customer_id
----------  -----------
(0 rows)
SELECT c.section_id, c.course_id
FROM sections AS c
LEFT JOIN courses AS p ON p.course_id = c.course_id
WHERE p.course_id IS NULL;
section_id  course_id
----------  ---------
(0 rows)

The result is empty: every child has its parent.

Worked example: products never sold

"Which products have never appeared on an order?"

Step Query part
all products FROM products AS p
try to find their order lines LEFT JOIN order_items AS i ON i.product_id = p.product_id
keep those with no line WHERE i.order_id IS NULL

Or: WHERE NOT EXISTS (SELECT 1 FROM order_items i WHERE i.product_id = p.product_id). In the Shop sample every product has been sold at least once, so the result is empty; the same query is how you would find the unsold ones. The tables are made up.

Common mistakes

  • Testing the wrong column for NULL. Use the child's primary key, not a column that may be NULL anyway.
  • NOT IN with a list that can contain NULL.
  • Using an inner join when you want the missing rows: they are exactly what it drops.
  • Not checking that the missing plus the present make the whole table.

Key takeaways

  • To find rows with no partner, use LEFT JOIN ... WHERE child.key IS NULL or NOT EXISTS.
  • NOT IN is dangerous when the list can contain NULL.
  • Missing plus present should equal the total; check it.
  • Swap the tables to find orphans on the other side.

Practice

1. Write the pattern for "customers with no orders".

Show answer

SELECT c.* FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id WHERE o.order_id IS NULL;

2. Why test the child's primary key for NULL?

Show answer

A primary key is never NULL for a real row, so NULL there can only mean "no match".

3. Rewrite the same question with NOT EXISTS.

Show answer

SELECT c.* FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);

4. Why can NOT IN return nothing at all?

Show answer

If the list from the subquery contains NULL, the comparison is unknown for every row.

5. What should "with children" plus "without children" add up to?

Show answer

The total number of parents.

6. Which join would drop the rows you are looking for?

Show answer

An inner join, because it keeps only rows that have a match.