Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Subqueries and WITH

By the end of this chapter, you'll be able to

  • Use a subquery that returns a value, or a list with IN
  • Write a correlated subquery
  • Split a query into named steps with WITH
  • Avoid the NOT IN trap with NULL values

A query inside the query

A subquery is written between parentheses. If it returns a single value, you use it like a number:

SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;
name | price
50 W panel | 70
Water filter | 40

If it returns a column of several values, test membership with IN:

SELECT name, city
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE status = 'delivered');
name | city
Aïcha | Abidjan
Bruno | Recife

A correlated subquery uses a column from the main query: it is recomputed for each row. Here, for each product, we look for the maximum price of its category:

SELECT p.name, p.category, p.price
FROM products AS p
WHERE p.price = (SELECT MAX(price) FROM products WHERE category = p.category)
ORDER BY p.category;
name | category | price
50 W panel | energy | 70
Water filter | water | 40

WITH: naming the steps

As soon as a query has several steps, nested subqueries become unreadable. A CTE (Common Table Expression) gives each step a name, which you then use like a table:

WITH amounts AS (
  SELECT o.id, o.customer_id, SUM(i.quantity * p.price) AS amount
  FROM orders AS o
  JOIN order_items AS i ON i.order_id = o.id
  JOIN products AS p ON p.id = i.product_id
  WHERE o.status <> 'cancelled'
  GROUP BY o.id
),
per_customer AS (
  SELECT customer_id, COUNT(*) AS nb, SUM(amount) AS total
  FROM amounts
  GROUP BY customer_id
)
SELECT c.name, pc.nb, pc.total, ROUND(pc.total / pc.nb, 2) AS average_basket
FROM per_customer AS pc
JOIN customers AS c ON c.id = pc.customer_id
ORDER BY pc.total DESC;
name | nb | total | average_basket
Aïcha | 3 | 184.5 | 61.5
Chen | 1 | 140 | 140
Bruno | 1 | 40 | 40

Final step: join the customers to display the names and compute the average basket.

Step 3 of 3
Text description of the animation
  1. First step: the amount of each non-cancelled order, thanks to the joins.
  2. Second step: these amounts are grouped by customer. The amounts CTE is used like a table.
  3. Final step: join the customers to display the names and compute the average basket.

Each step can be read and tested separately: replace the final SELECT with SELECT * FROM amounts to check the first one. It's the best tool for debugging a complex query.

Your turn

Mini-lab: orders above averageSQLite

Result

Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.

A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Solved exercise: the best product in each category

For each category, display the product ordered in the largest quantity (all orders except cancelled ones), with that quantity.

Hint 1
Start with a sold CTE that computes each product's total quantity, with its category.
Hint 2
Then keep the rows of sold whose quantity equals the maximum of their category, with a correlated subquery on sold.
Show the solution and common mistakes
WITH sold AS (
  SELECT p.name, p.category, SUM(i.quantity) AS quantity
  FROM order_items AS i
  JOIN products AS p ON p.id = i.product_id
  JOIN orders AS o ON o.id = i.order_id
  WHERE o.status <> 'cancelled'
  GROUP BY p.id
)
SELECT s.category, s.name, s.quantity
FROM sold AS s
WHERE s.quantity = (SELECT MAX(quantity) FROM sold WHERE category = s.category)
ORDER BY s.category;
category | name | quantity
energy | Solar lamp | 6
water | Water filter | 2

In case of a tie, both products would be displayed: that's often what you want. The window functions chapter of the advanced course shows how to keep only one.

Common mistakes:

  • Putting MAX(quantity) directly in the main query's WHERE: misuse of aggregate, as in the previous course.
  • Forgetting the correlation WHERE category = s.category: you get the maximum across all categories, and only one product is displayed.

Summary

  1. 1A subquery that returns one value is used like a number; a list is used with IN.
  2. 2A correlated subquery uses a column of the main query and is recomputed for each row.
  3. 3WITH splits a query into named steps, readable and testable separately.
  4. 4NOT IN returns an empty result if the subquery contains NULL: prefer NOT EXISTS.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.