Chain CTEs
Your task
First summarize sales by album, then keep totals of at least three. Return album IDs and filtered totals.
Later CTEs can reference earlier CTEs in the same WITH clause.
Sample data
sales| id | album_id | quantity |
|---|---|---|
| 101 | 1 | 2 |
| 102 | 2 | 1 |
| 103 | 1 | 3 |
| 104 | 4 | 2 |
| 105 | 5 | 1 |
| 106 | 2 | 2 |
Expected output
| album_id | copies |
|---|---|
| 1 | 5 |
| 2 | 3 |
Show a hint
Define totals, then strong_sales AS (SELECT * FROM totals WHERE copies >= 3).
Subqueries and CTEs guide
Use a query as a value
An aggregate without GROUP BY produces one row. A single-column subquery can therefore provide a scalar value for a comparison. Here each price is compared with an average calculated across the whole table.
SELECT title, price
FROM albums
WHERE price < (SELECT AVG(price) FROM albums);Ask whether a related row exists
An EXISTS subquery only needs to produce one row to be true. It refers to a.id from the outer query, so the test is evaluated for the current album. The expression in the inner SELECT is immaterial to the existence test.
SELECT a.title
FROM albums AS a
WHERE EXISTS (
SELECT 1
FROM sales AS s
WHERE s.album_id = a.id AND s.quantity > 1
);Name intermediate results with WITH
A common table expression gives an intermediate query a name for a single statement. Here the CTE summarizes sales before joining them to albums. Read the CTE on its own first, then read the final SELECT to see how the summary is used.
WITH totals AS (
SELECT album_id, SUM(quantity) AS copies
FROM sales
GROUP BY album_id
)
SELECT a.title, COALESCE(t.copies, 0) AS copies
FROM albums AS a
LEFT JOIN totals AS t ON t.album_id = a.id;Worked solution
WITH totals AS (SELECT album_id, SUM(quantity) AS copies FROM sales GROUP BY album_id), strong_sales AS (SELECT * FROM totals WHERE copies >= 3) SELECT album_id, copies FROM strong_sales;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
