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.

30 min 3 practice tasks
SQL WITH Clause | Clearly Explained | CTEs vs Subqueries vs Temp Tables | Recursive CTEs by Maven Analytics on YouTube

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.

1

Unusually large orders

Find 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?
  1. WHERE works row by row, so it can't use AVG directly.
  2. Compute the average in parentheses: (SELECT AVG(amount) FROM orders WHERE status = 'completed'). Don't forget the status filter inside it too.
SQL · SQLite
SELECT id, customer_id, amount
FROM orders
WHERE status = 'completed'
  AND amount > 2 * AVG(amount);
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
2

Campaigns that lost money

Which 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?
  1. Treat campaign_totals like a table. Join it to campaigns to get the name.
  2. Because the totals already exist in the CTE, a plain WHERE t.revenue < t.spend works (no HAVING needed).
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
3

Customer value tiers

Segment 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?
  1. Add a second CTE after a comma: WITH a AS (...), b AS (SELECT ... FROM a).
  2. In the second step, use a CASE on total; in the final SELECT, group by the tier.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue