Subqueries and CTEs · Lesson 56 of 64

SQL Choosing Between Joins, Subqueries and CTEs

What you will learn

  • That the same question has several correct queries
  • How to choose by clarity, safety and speed
  • How to compare two queries (results and plan)
  • A checklist for a query that is hard to read

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. One question, four queries

"How many customers have at least one (order / account / enrollment)?" Four ways to ask it:

-- 1. join with DISTINCT
SELECT COUNT(DISTINCT o.customer_id) AS customers FROM orders AS o JOIN customers AS c ON c.customer_id = o.customer_id;
customers
---------
      365
(1 row)
-- 2. IN
SELECT COUNT(*) AS customers FROM customers WHERE customer_id IN (SELECT customer_id FROM orders);
customers
---------
      365
(1 row)
-- 3. EXISTS
SELECT COUNT(*) AS customers FROM customers AS c WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);
customers
---------
      365
(1 row)
-- 4. WITH
WITH buyers AS (SELECT DISTINCT customer_id FROM orders)
SELECT COUNT(*) AS customers FROM buyers;
customers
---------
      365
(1 row)
-- 1. join with DISTINCT
SELECT COUNT(DISTINCT a.customer_id) AS customers FROM accounts AS a JOIN customers AS c ON c.customer_id = a.customer_id;
customers
---------
      236
(1 row)
-- 2. IN
SELECT COUNT(*) AS customers FROM customers WHERE customer_id IN (SELECT customer_id FROM accounts);
customers
---------
      236
(1 row)
-- 3. EXISTS
SELECT COUNT(*) AS customers FROM customers AS c WHERE EXISTS (SELECT 1 FROM accounts AS a WHERE a.customer_id = c.customer_id);
customers
---------
      236
(1 row)
-- 4. WITH
WITH owners AS (SELECT DISTINCT customer_id FROM accounts)
SELECT COUNT(*) AS customers FROM owners;
customers
---------
      236
(1 row)
-- 1. join with DISTINCT
SELECT COUNT(DISTINCT e.student_id) AS students FROM enrollments AS e JOIN students AS s ON s.student_id = e.student_id;
students
--------
     340
(1 row)
-- 2. IN
SELECT COUNT(*) AS students FROM students WHERE student_id IN (SELECT student_id FROM enrollments);
students
--------
     340
(1 row)
-- 3. EXISTS
SELECT COUNT(*) AS students FROM students AS s WHERE EXISTS (SELECT 1 FROM enrollments AS e WHERE e.student_id = s.student_id);
students
--------
     340
(1 row)
-- 4. WITH
WITH enrolled AS (SELECT DISTINCT student_id FROM enrollments)
SELECT COUNT(*) AS students FROM enrolled;
students
--------
     340
(1 row)

All four give the same number. When different ways give different answers, one of them is wrong; that is a useful check.

2. How to choose

Choose When
join you need columns from the other table
IN a simple "is it in this list?" and the list column has no NULL
EXISTS / NOT EXISTS "has a match" or "has no match", especially with possible NULLs
WITH several steps, or the same step used twice
correlated subquery each row compared with its own group, on a small or indexed table
view the step is shared by many queries

Most of the time, pick the one you can read and explain. Modern databases rewrite these forms into similar plans.

3. Compare the plans

EXPLAIN QUERY PLAN shows how SQLite will run each. Compare the join form and the EXISTS form:

EXPLAIN QUERY PLAN
SELECT COUNT(*) FROM customers AS c WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);
plan
--------------------------------------------------------
SCAN c USING COVERING INDEX sqlite_autoindex_customers_1
CORRELATED SCALAR SUBQUERY 1
SCAN o
(3 rows)
EXPLAIN QUERY PLAN
SELECT COUNT(*) FROM customers AS c WHERE EXISTS (SELECT 1 FROM accounts AS a WHERE a.customer_id = c.customer_id);
plan
----------------------------
SCAN c
CORRELATED SCALAR SUBQUERY 1
SCAN a
(3 rows)
EXPLAIN QUERY PLAN
SELECT COUNT(*) FROM students AS s WHERE EXISTS (SELECT 1 FROM enrollments AS e WHERE e.student_id = s.student_id);
plan
---------------------------------------------------------------------------
SCAN s USING COVERING INDEX sqlite_autoindex_students_1
CORRELATED SCALAR SUBQUERY 1
SEARCH e USING COVERING INDEX sqlite_autoindex_enrollments_1 (student_id=?)
(3 rows)

A correlated subquery shows a CORRELATED SCALAR SUBQUERY or a SEARCH ... USING INDEX on the inner table. Add an index on the linking column (lesson 6.6) and run the plan again to see it change. Plans differ between database systems and versions, so read them as a hint, not a promise.

4. A checklist for a hard query

  1. Say the question in one plain sentence.
  2. Find the grain: what does one output row stand for?
  3. Write the smallest query that gives the first step; look at its rows.
  4. Add one step at a time as a CTE with a good name.
  5. Check the row count after every join (does it grow when it should not?).
  6. Compare with a second way to ask it (a different form) and see that the numbers agree.
  7. Only then think about speed: plan, indexes, and removing repeated work.

Worked example: rewriting a long query

A report query has three nested subqueries and nobody understands it.

Step Do
1 write the question in words and the grain of the output
2 turn the innermost subquery into the first CTE, check its rows
3 turn the next level into the second CTE using the first
4 the final SELECT joins the CTEs; compare its numbers with the old query

If the numbers agree, the rewrite is right and the query can be explained. The query is made up.

Common mistakes

  • Choosing the cleverest form instead of the clearest.
  • NOT IN over a nullable column.
  • Never comparing with a second way to ask the same thing.
  • Optimising before checking the result.
  • Believing a form is always faster in every database.

Key takeaways

  • One question has several correct queries; they must agree on the numbers.
  • Use a join for columns, IN/EXISTS for matches, WITH for steps, a view for shared steps.
  • Prefer the form you can read and explain; check the plan before worrying about speed.
  • Rewrite hard queries step by step with named CTEs, checking the rows at each step.

Practice

1. Name four ways to find customers who have at least one order.

Show answer

A join with DISTINCT, IN (subquery), EXISTS, and a WITH query.

2. Which form is safest for "has no match"?

Show answer

NOT EXISTS (or LEFT JOIN ... IS NULL), not NOT IN over a nullable column.

3. Four forms give four different numbers. What does that tell you?

Show answer

At least one query is wrong, or they answer slightly different questions; find out which.

4. What is the "grain" of a query?

Show answer

What one output row stands for, for example one customer or one order line.

5. When do you reach for a view instead of a CTE?

Show answer

When many queries share the same step.

6. What do you do before optimising?

Show answer

Check that the result is correct, ideally by comparing with a second way to ask the same question.