4. Data engineering patterns
4.5 Subqueries: a query inside a query
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
"Show the orders that are bigger than the average order." To answer, you first need the average. That is one query. Then you compare each order with it. That is a second query. A subquery lets you write both in one statement.
A subquery sits inside brackets. The database runs the inner query first and hands its answer to the outer query.
- It can return one value: use it with >, < or =
- It can return a list: use it with IN
NOT IN (subquery) returns nothing if the subquery's list contains a NULL. When the column can be NULL, filter the NULLs out inside the subquery or use NOT EXISTS.
Bigger than average
The inner query runs first.
SQL
SELECT id, amountFROM ordersWHERE amount > (SELECT AVG(amount) FROM orders)ORDER BY amount DESC;
Rows at this step
id | amount ----+------- 101 | 55000 105 | 52000
Quick check
Which part runs first?
A list from a subquery
Customers who have at least one delivered order.
SQL
SELECT nameFROM customersWHERE id IN (SELECT customer_id FROM orders WHERE status = 'delivered')ORDER BY name;
Rows at this step
name ---- Asha Ravi
Quick check
The subquery returns the list 1, 2, 1, 2, 1. How many customers does id IN (...) keep?
Practice in SQL ✓ Solved
Show the names of the customers who have no orders. Use NOT IN with a subquery.
Tables you can query: customers, orders
customers id | name | city ---+-------+------ 1 | Asha | Noida 2 | Ravi | Delhi 3 | Meera | Pune 4 | Kabir | Noida 5 | Zoya | NULL orders id | customer_id | product | amount | status | order_date ----+-------------+----------+--------+-----------+----------- 101 | 1 | Laptop | 55000 | delivered | 2026-01-05 102 | 2 | Mouse | 700 | delivered | 2026-01-06 103 | 1 | Keyboard | 1500 | delivered | 2026-01-09 104 | 3 | Monitor | 12000 | cancelled | 2026-01-12 105 | 2 | Laptop | 52000 | delivered | 2026-01-15 106 | 4 | Mouse | 650 | pending | 2026-01-18 107 | 1 | Monitor | 11500 | delivered | 2026-01-20 108 | 3 | Keyboard | NULL | pending | 2026-01-22
Expected output
name ---- Zoya
Reference solution
SELECT name
FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
Question 1 · Easy
Where does a subquery sit?
Question 2 · Medium
amount > (SELECT AVG(amount) FROM orders) needs the subquery to return…
Question 3 · Hard
When can NOT IN (subquery) surprise you with zero rows?
Key takeaways
A subquery is a query in brackets that runs first. Use a one-value subquery with comparisons and a list subquery with IN. Watch for NULLs with NOT IN.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in