Section 4 · Lesson 1
Subqueries and CTEs
Use the result of one query inside another, and break complex analysis into readable named steps with WITH.
As questions get harder, a single SELECT stops being enough. “Orders bigger than the average
order” needs the average first. “Campaigns that lost money” needs per-campaign totals first. SQL
lets you use the result of one query inside another, either as a subquery or as a named step
called a CTE.
Subqueries: a query inside a query
A subquery is a complete SELECT in parentheses. Where you put it decides what it does.
A single value in WHERE (a scalar subquery):
-- Campaigns with a budget above the average budget
SELECT name, daily_budget
FROM campaigns
WHERE daily_budget > (SELECT AVG(daily_budget) FROM campaigns);
The inner query runs first and becomes one number. You can’t write WHERE daily_budget > AVG(daily_budget) directly, because WHERE looks at one row at a time.
A list in IN:
-- Customers who bought through a video campaign
SELECT first_name, last_name
FROM customers
WHERE id IN (SELECT o.customer_id
FROM orders AS o
JOIN campaigns AS c ON c.id = o.campaign_id
WHERE c.channel = 'video');
A table in FROM (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;
CTEs: name your steps with WITH
Nested parentheses get hard to read fast. A common table expression (CTE) moves the inner query to the top and gives it a name:
WITH per_customer AS (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
)
SELECT AVG(order_count) AS avg_orders_per_customer
FROM per_customer;
Same result, but it reads top to bottom like a recipe: first build per_customer, then use
it. A CTE exists only while this one statement runs. It doesn’t create anything in the
database.
Several steps in a row
Chain CTEs with commas. Each one can use the ones defined before it:
WITH campaign_totals AS (
SELECT campaign_id, SUM(spend) AS spend, SUM(revenue) AS revenue
FROM daily_stats
GROUP BY campaign_id
),
order_totals AS (
SELECT campaign_id, COUNT(*) AS orders
FROM orders
WHERE status = 'completed'
GROUP BY campaign_id
)
SELECT c.name, ROUND(t.spend, 2) AS spend, o.orders
FROM campaigns AS c
JOIN campaign_totals AS t ON t.campaign_id = c.id
LEFT JOIN order_totals AS o ON o.campaign_id = c.id
ORDER BY spend DESC;
This is the fix for the double-counting trap from the joins section. Each “many” table
(daily_stats, orders) is first squeezed down to one row per campaign, so joining the
summaries can’t multiply anything.
When to use which
| Situation | Good choice |
|---|---|
| Compare each row to one overall number | scalar subquery |
| “Is this id in that list?” | IN (subquery) or EXISTS |
| Multi-step logic, or a step reused twice | CTE |
| Anything a teammate will need to read later | CTE |
Performance is usually the same in modern databases, so choose for readability. A good habit is to build a CTE step, run it on its own to check the numbers, then add the next step on top. Debugging a 40-line query is much easier when each named piece has been checked.
About the video: the CTE and subquery syntax shown is standard and works in SQLite. Temporary tables also exist in SQLite (
CREATE TEMP TABLE), but in this course’s sandbox you’ll stick to CTEs.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Unusually large orders
DoneFind completed orders whose amount is more than twice the average amount of all completed orders. Return id, customer_id and amount. The starter fails with an error; replace the aggregate with a subquery.
Need a hint?
WHEREworks row by row, so it can't useAVGdirectly.- Compute the average in parentheses:
(SELECT AVG(amount) FROM orders WHERE status = 'completed'). Don't forget the status filter inside it too.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT id, customer_id, amount
FROM orders
WHERE status = 'completed'
AND amount > 2 * AVG(amount);
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Campaigns that lost money
DoneWhich campaigns brought in less revenue than they spent? Using a CTE that totals spend and revenue per campaign from daily_stats, return the campaign name, total spend and total revenue (both rounded to 2 decimals) for campaigns where total revenue is below total spend. Sort by total spend, highest first.
Need a hint?
- Treat
campaign_totalslike a table. Join it tocampaignsto get the name. - Because the totals already exist in the CTE, a plain
WHERE t.revenue < t.spendworks (no HAVING needed).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
WITH campaign_totals AS (
SELECT campaign_id,
SUM(spend) AS spend,
SUM(revenue) AS revenue
FROM daily_stats
GROUP BY campaign_id
)
SELECT campaign_id, ROUND(spend, 2) AS spend, ROUND(revenue, 2) AS revenue
FROM campaign_totals;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Customer value tiers
DoneSegment customers by lifetime value. Consider only completed orders and only customers with at least one of them. First total each customer's completed amount; then label each customer high (total of 500 or more), medium (200 or more) or low (under 200); then count customers per tier. Return the tier and the number of customers, sorted by number of customers, highest first.
Need a hint?
- Add a second CTE after a comma:
WITH a AS (...), b AS (SELECT ... FROM a). - In the second step, use a CASE on
total; in the final SELECT, group by the tier.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
WITH customer_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
)
SELECT *
FROM customer_totals;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)