Subqueries and CTEs · Lesson 50 of 64

SQL IN and EXISTS with Subqueries

What you will learn

  • How IN (SELECT ...) filters by a list built by a query
  • Why NOT IN can go wrong with NULL
  • How EXISTS and NOT EXISTS work
  • How they compare with a join

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. IN with a subquery

IN accepts a list of values (lesson 2.3). The list can come from a query that returns one column:

Customers who have placed at least one order:

SELECT customer_id, first_name, last_name FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders)
ORDER BY customer_id LIMIT 4;
customer_id  first_name  last_name
-----------  ----------  ---------
          1  Vik         Ahmed
          2  Wanda       Ahmed
          3  Dana        Costa
          4  Noah        Nair
(4 rows)

Customers who own at least one account:

SELECT customer_id, full_name FROM customers
WHERE customer_id IN (SELECT customer_id FROM accounts)
ORDER BY customer_id LIMIT 4;
customer_id  full_name
-----------  -----------
          1  Chen Park
          3  Grace Kamau
          5  Farid Lee
          7  Olga Garcia
(4 rows)

Students who have at least one enrollment:

SELECT student_id, first_name, last_name FROM students
WHERE student_id IN (SELECT student_id FROM enrollments)
ORDER BY student_id LIMIT 4;
student_id  first_name  last_name
----------  ----------  ---------
         1  Vera        Khan
         2  Elena       Haque
         3  Chloe       Garcia
         4  Quinn       Meyer
(4 rows)

Duplicates in the inner result do not matter: IN only asks "is the value in the list?". A customer with ten orders still appears once, which a plain join would not do.

2. NOT IN: those without

"Who has no orders?" is NOT IN:

SELECT COUNT(*) AS customers_without_orders FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);
customers_without_orders
------------------------
                      55
(1 row)
SELECT COUNT(*) AS customers_without_accounts FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM accounts);
customers_without_accounts
--------------------------
                        64
(1 row)
SELECT COUNT(*) AS students_without_enrollments FROM students
WHERE student_id NOT IN (SELECT student_id FROM enrollments);
students_without_enrollments
----------------------------
                          20
(1 row)

3. The NOT IN and NULL trap

If the inner list contains even one NULL, NOT IN returns no rows at all: the comparison with the unknown value is never true (lesson 2.5):

SELECT 5 NOT IN (1, 2, 3) AS clean_list, 5 NOT IN (1, 2, NULL) AS list_with_null;
clean_list  list_with_null
----------  --------------
         1  NULL
(1 row)
SELECT 5 NOT IN (1, 2, 3) AS clean_list, 5 NOT IN (1, 2, NULL) AS list_with_null;
clean_list  list_with_null
----------  --------------
         1  NULL
(1 row)
SELECT 5 NOT IN (1, 2, 3) AS clean_list, 5 NOT IN (1, 2, NULL) AS list_with_null;
clean_list  list_with_null
----------  --------------
         1  NULL
(1 row)

The second answer is NULL (unknown), so a WHERE would reject the row. The safe habits: filter the NULLs out of the inner query (WHERE col IS NOT NULL), or use NOT EXISTS.

4. EXISTS

EXISTS (subquery) is true when the subquery returns at least one row. What the subquery selects does not matter, so SELECT 1 is the convention. The inner query refers to the outer row, which is what links them:

SELECT c.customer_id, c.first_name FROM customers AS c
WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id)
ORDER BY c.customer_id LIMIT 4;
customer_id  first_name
-----------  ----------
          1  Vik
          2  Wanda
          3  Dana
          4  Noah
(4 rows)
SELECT c.customer_id, c.full_name FROM customers AS c
WHERE EXISTS (SELECT 1 FROM accounts AS a WHERE a.customer_id = c.customer_id)
ORDER BY c.customer_id LIMIT 4;
customer_id  full_name
-----------  -----------
          1  Chen Park
          3  Grace Kamau
          5  Farid Lee
          7  Olga Garcia
(4 rows)
SELECT s.student_id, s.first_name FROM students AS s
WHERE EXISTS (SELECT 1 FROM enrollments AS e WHERE e.student_id = s.student_id)
ORDER BY s.student_id LIMIT 4;
student_id  first_name
----------  ----------
         1  Vera
         2  Elena
         3  Chloe
         4  Quinn
(4 rows)

5. NOT EXISTS

NOT EXISTS keeps the rows with no match. It is not hurt by NULLs, so it is the safe way to find "those without":

SELECT COUNT(*) AS customers_without_orders FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);
customers_without_orders
------------------------
                      55
(1 row)
SELECT COUNT(*) AS customers_without_accounts FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM accounts AS a WHERE a.customer_id = c.customer_id);
customers_without_accounts
--------------------------
                        64
(1 row)
SELECT COUNT(*) AS students_without_enrollments FROM students AS s
WHERE NOT EXISTS (SELECT 1 FROM enrollments AS e WHERE e.student_id = s.student_id);
students_without_enrollments
----------------------------
                          20
(1 row)

The count matches the NOT IN one above, as it should here, because the inner column has no NULL.

6. Which one to use

Question Good choices
keep rows that have a match IN (subquery), EXISTS, or a join with DISTINCT
keep rows with no match NOT EXISTS, or LEFT JOIN ... IS NULL (lesson 4.4)
the inner column may contain NULL EXISTS / NOT EXISTS, not NOT IN

Modern databases usually plan IN and EXISTS equally well, so choose by clarity and safety.

Worked example: customers who never ordered

Step Do
1 the parent table is customers, the related table is orders
2 the link is o.customer_id = c.customer_id
3 write WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id)
4 compare the count with the LEFT JOIN ... IS NULL version

Two different ways, one answer: a good check. The tables are from the Shop sample.

Common mistakes

  • NOT IN over a column that can be NULL.
  • An EXISTS subquery without the link to the outer row, which is true for everybody or nobody.
  • A subquery with more than one column in IN.
  • Using a join and forgetting that it repeats rows where IN would not.

Key takeaways

  • IN (SELECT col ...) filters by a list built by a query; duplicates do not matter.
  • NOT IN returns nothing if the list contains NULL; filter the NULLs or use NOT EXISTS.
  • EXISTS is true when the subquery returns a row; it needs a link to the outer row.
  • NOT EXISTS is the safe way to find rows without a match.

Practice

1. Write the condition for customers who appear in orders.

Show answer

WHERE customer_id IN (SELECT customer_id FROM orders)

2. What does 5 NOT IN (1, 2, NULL) give?

Show answer

NULL (unknown), so a WHERE rejects the row.

3. Why does SELECT 1 work inside EXISTS?

Show answer

EXISTS only checks whether a row exists, not what it contains.

4. Which keeps customers who have no orders: EXISTS or NOT EXISTS?

Show answer

NOT EXISTS.

5. Why can IN give fewer rows than a join?

Show answer

A join repeats the outer row for each match, while IN keeps each outer row once.

6. What is the safe habit for "rows without a match"?

Show answer

Use NOT EXISTS (or a LEFT JOIN ... IS NULL), not NOT IN over a column that may hold NULL.