Subqueries and Common Table Expressions
Nest one query inside another with subqueries, use IN and EXISTS to filter by related data, and write readable multi-step queries with WITH.
Welcome back!
Step 1 of 15Learn
A query inside a query
Some questions need an answer from one query before you can write another. "Which books cost more than the average price?" First you need the average; then you compare each book with it. A subquery does both at once:
SELECT title, price
FROM books
WHERE price > (SELECT AVG(price) FROM books);The inner query runs first and returns a single value, about 22.81. The outer query then keeps books priced above it: Data in Practice (42.00), Learning to Cook (24.00) and Quiet Numbers (35.00). The Last Signal, at 21.00, falls just short.
A subquery that returns exactly one value is a scalar subquery, and it can go anywhere a single value can: in WHERE, in SELECT, even in calculations:
SELECT title, price,
price - (SELECT AVG(price) FROM books) AS diff_from_avg
FROM books;Subqueries that return a list of values pair with IN. Which customers have placed an order over $40?
SELECT name
FROM customers
WHERE customer_id IN (
SELECT customer_id FROM orders WHERE total > 40
);The inner query returns customer IDs 3 and 4 (orders 102 and 104), so the result is Lena Ortiz and Marcus Lee.
Subqueries can also appear in FROM, where the inner result acts as a temporary table, called a derived table, which must be given an alias:
SELECT AVG(order_count) AS avg_orders_per_customer
FROM (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) AS per_customer;The inner query gives counts of 3, 1, 1 and 1 for the four ordering customers; the outer query averages them to 1.5.
Step 2 of 15Diagram
How a scalar subquery runs
Tap a shape with to see more.
- Inner: SELECT AVG(price)
Runs first and produces one value.
- Result: 22.81
The subquery is replaced by this single number.
- Outer: WHERE price > 22.81
Each book is compared with that value.
- 3 titles returned
Data in Practice, Learning to Cook, Quiet Numbers.
Step 3 of 15Practice · Work it out
Using the books table (average price about 22.81), how many rows does this query return? SELECT title FROM books WHERE price < (SELECT AVG(price) FROM books);
Step 4 of 15Practice · Chart
Book prices compared with the average (22.81)
Which book only just passes WHERE price > (SELECT AVG(price) FROM books)?
Tap the bar that answers the question, then press Check.
Step 5 of 15Note
Step 6 of 15Learn
EXISTS, NOT EXISTS and the NOT IN trap
EXISTS tests whether a subquery returns any rows at all. It's often used with a correlated subquery, one that refers to the outer query's current row:
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);For each customer, the inner query looks for at least one of their orders. Result: Priya, Tom, Lena and Marcus. NOT EXISTS gives the opposite, customers with no orders (Ava), an alternative to the LEFT JOIN pattern from the last lesson.
The SELECT 1 inside is a convention: EXISTS only cares whether rows exist, not what columns they contain.
Now a trap that catches experienced developers. To find customers with no orders, you might write:
SELECT name FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);That works here. But if the subquery's list ever contains a NULL, say an order row with a missing customer_id, NOT IN returns no rows at all. That's because "5 NOT IN (1, 2, NULL)" means "5 ≠ 1 AND 5 ≠ 2 AND 5 ≠ NULL," and the last comparison is unknown, making the whole condition unknown. NOT EXISTS doesn't have this problem, which is why many style guides prefer it for "has no matching rows" questions.
When to use which:
- Scalar subquery: compare with a single computed value, like an average or maximum.
- IN: filter by a list from another table, when the list has no NULLs.
- EXISTS / NOT EXISTS: check whether related rows exist, safely.
- JOIN: when you need columns from both tables in the output.
Step 7 of 15Practice · Code challenge · SQL
Code challenge · SQL
Return the title and price of every book that costs more than the average price of all books.
Do not type the average in by hand: let a subquery compute it, so the query stays correct when prices change.
The database for this exercise (tables and rows)
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
genre TEXT,
price REAL,
year INTEGER,
stock INTEGER
);
INSERT INTO books VALUES
(1, 'The Silent Orbit', 'Mara Quinn', 'Sci-Fi', 18.00, 2019, 12),
(2, 'Gardens of Salt', 'Leo Park', 'Fiction', 15.50, 2021, 0),
(3, 'Data in Practice', 'Ana Ruiz', 'Tech', 42.00, 2022, 7),
(4, 'Night Ferry', 'Leo Park', 'Mystery', 12.99, 2017, 25),
(5, 'Learning to Cook', 'Sam Odell', 'Food', 24.00, 2020, 3),
(6, 'The Last Signal', 'Mara Quinn', 'Sci-Fi', 21.00, 2023, 9),
(7, 'Quiet Numbers', 'Ana Ruiz', 'Tech', 35.00, 2018, NULL),
(8, 'River Road', 'Jo Banks', 'Fiction', 14.00, 2016, 18);- Result matches the expected table
Step 8 of 15Practice · Choose one
Why can NOT IN with a subquery unexpectedly return no rows?
Step 9 of 15Learn
CTEs: name your steps with WITH
As questions grow, nested subqueries become hard to read, with logic buried inside parentheses inside parentheses. A common table expression (CTE) lets you define named steps at the top of the query with WITH, then use them like tables:
WITH customer_totals AS (
SELECT customer_id, COUNT(*) AS num_orders, SUM(total) AS spent
FROM orders
GROUP BY customer_id
)
SELECT c.name, t.num_orders, t.spent
FROM customer_totals t
JOIN customers c ON c.customer_id = t.customer_id
WHERE t.spent > 40
ORDER BY t.spent DESC;Read it top to bottom like a recipe: first compute each customer's totals, then attach names and filter. Result: Priya Shah (3 orders, 69.99), Marcus Lee (1, 59.50) and Lena Ortiz (1, 42.00). Tom, at 24.00, is filtered out.
You can define several CTEs, separated by commas, and each can use the ones before it:
WITH customer_totals AS (
SELECT customer_id, SUM(total) AS spent
FROM orders GROUP BY customer_id
),
big_spenders AS (
SELECT customer_id FROM customer_totals WHERE spent > 50
)
SELECT c.name
FROM customers c
JOIN big_spenders b ON b.customer_id = c.customer_id;This returns Priya and Marcus.
CTEs don't make queries faster or slower in most modern databases; their value is readability and debuggability. You can run each step on its own to check it before building the next. That habit, building complex queries in small, verified steps, is one of the best things you can take from this course. (CTEs also enable recursive queries for hierarchies such as org charts, an advanced topic for later.)
Step 10 of 15Practice · Diagram
A CTE as a pipeline of named steps
WITH customer_totals AS (...), big_spenders AS (...) SELECT ... reads top to bottom. Tap each step.
Which named step can you run on its own first to check the per-customer sums?
Tap the shape that answers the question, then press Check.
- orders table
The raw rows.
- customer_totals
SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id
- big_spenders
SELECT * FROM customer_totals WHERE spent > 50: customers 1 and 4.
- Final SELECT + JOIN
Join big_spenders to customers to show names: Priya Shah, Marcus Lee.
Step 11 of 15Compare
Subquery, EXISTS or CTE?
| Aspect | Scalar subquery | EXISTS | CTE (WITH) |
|---|---|---|---|
| Returns | One value | True or false per outer row | A named temporary result |
| Typical use | Compare with an average or max | "Has at least one" / "has none" | Multi-step logic |
| NULL trap | Empty result becomes NULL | Safe with NOT EXISTS | Depends on the inner queries |
| Readability | Fine when short | Fine when short | Best for long queries |
Step 12 of 15Practice · Put in order
Arrange the lines of this CTE query in a valid order.
Drag the items, or use the arrow buttons, to put them in order.
- WITH genre_stats AS (
- WHERE avg_price > 20;
- SELECT genre, AVG(price) AS avg_price FROM books GROUP BY genre
- SELECT genre, avg_price FROM genre_stats
- )
Step 13 of 15Note
Step 14 of 15Practice · Select all that apply
Using the customers and orders tables, which queries return the names of customers who have placed at least one order? Select all that apply.
Select all that apply.
Step 15 of 15Practice · True or false
A scalar subquery, such as (SELECT AVG(price) FROM books), can be used in a WHERE clause to compare each row with a single computed value.
Lesson complete!