Thuta Learning
SQL
AdvancedData & DatabasesBeginner

Subqueries & Common Table Expressions

SQLLesson 2030 min

What you'll walk away with

  • Tell where a subquery may go depending on whether it returns one value, a list or a table
  • Filter on an aggregate result by splitting the query into a CTE or a derived table
  • Write a correlated subquery that refers to the current outer row
  • Chain several CTEs so a query reads top to bottom

Explain it simply

Explain it simply

When cooking, you fry the onions first and then add those fried onions to the curry. A subquery works the same way: a small query runs first and its result becomes an ingredient of the bigger query. For "products priced above average", you compute the average first and then compare against it.

A CTE, or Common Table Expression, gives those steps names and writes them at the top of the query with WITH. Like a recipe that says "step 1: fry the onions", the query can then be read step by step from top to bottom.

Problem → Why → Solution

The problem: WHERE cannot see aggregate results

You want the customers whose orders add up to at least 1000. You compute each customer's SUM(amount) with GROUP BY and filter it in WHERE, and PostgreSQL raises an error. Using the alias total instead fails with "column total does not exist".

big_spenders.sql
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE SUM(amount) >= 1000          -- ERROR: aggregate functions are not
GROUP BY customer_id;              --        allowed in WHERE

SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE total >= 1000                -- ERROR: column "total" does not exist
GROUP BY customer_id;

Why can't WHERE see it?

SQL does not run clauses in the order you write them: it goes FROM, WHERE, GROUP BY, then SELECT. When WHERE runs, no groups exist yet, so there is no SUM, and the alias total from SELECT has not been born. The fix is to split the query into two stages: the first computes total, and the second filters that result with WHERE as if it were an ordinary table. HAVING is another option, covered in the GROUP BY lesson.

Core concept: the shape of a subquery's result decides where it fits

A subquery is a SELECT inside parentheses, and the shape of its result decides where it may appear. A scalar subquery returns one row and one column, a single value, so it fits anywhere a number would, as in WHERE amount > (SELECT AVG(amount) FROM orders). If it ever returns more than one row, PostgreSQL raises "more than one row returned by a subquery used as an expression".

A subquery that returns one column and many rows, a list, pairs with IN: WHERE customer_id IN (SELECT customer_id FROM orders WHERE amount >= 600). EXISTS ignores the values and only checks whether at least one row comes back. A subquery returning many rows and columns, a table, can go in FROM as a derived table that you SELECT from, filter and join like any other table. PostgreSQL 16 and later accept a derived table without an alias, but older versions and most other databases require one, so always write one, such as AS t.

A correlated subquery refers to a column of the outer query. For "each customer's largest order", the subquery uses o2.customer_id = o.customer_id to look only at the current outer row's customer. Conceptually it runs once per outer row; in practice PostgreSQL rewrites it into a join when it can.

A CTE moves a subquery to the top of the statement and names it: WITH totals AS (...) SELECT ... FROM totals. Several CTEs can be chained with commas, and a later CTE may refer to an earlier one. A CTE lives for exactly one statement; after the semicolon, totals no longer exists. Since PostgreSQL 12, a plain CTE referenced only once is inlined into the outer query and optimized with it, so using CTEs for readability usually costs nothing.

Result shapeWhere it fits
One value (scalar)SELECT list, WHERE amount > (...)
One column, many rows (list)WHERE x IN (...), NOT IN
Rows exist or notWHERE EXISTS (...), NOT EXISTS
A whole tableFROM (...) AS t, or WITH name AS (...)
Mental model: inner result feeds outer query
  1. Run the inner query first
  2. Note its shape: value, list or table
  3. The outer query uses it as an input
  4. A CTE is that step given a name

For a correlated subquery, picture the inner query re-running once for every outer row.

General pattern

sql
-- subquery as a value, a list, or a table
SELECT column_name FROM table_name
WHERE number_column > (SELECT AVG(number_column) FROM table_name)
  AND key_column IN (SELECT key_column FROM other_table WHERE condition);

-- the same idea as named steps
WITH step_one AS (
  SELECT key_column, SUM(number_column) AS total
  FROM table_name GROUP BY key_column
)
SELECT key_column, total FROM step_one WHERE total >= threshold;

In the first form, the scalar subquery acts as a single value and the IN subquery as a list. In the second, WITH names the aggregate result step_one, a temporary table for this statement, and the SELECT below filters it with WHERE.

Example: customers who spent 1000 or more

This answers the problem section's question with a CTE. The four customers' totals are Aye Aye (1) 1150.00, Bo Bo (2) 300.00, Chit Su (3) exactly 1000.00, and Daw Hla (4) 2500.00. Chit Su sits exactly on the 1000 boundary, so watch whether >= includes her.

big_spenders.sql
WITH totals AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  GROUP BY customer_id
)
SELECT customer_id, total
FROM totals
WHERE total >= 1000
ORDER BY total DESC, customer_id;

Code breakdown

  1. Lines 1-5WITH totals AS (

    The CTE totals returns one row per customer with their total, usable like a table inside this statement.

  2. Line 2SELECT customer_id, SUM(amount) AS total

    Together with GROUP BY customer_id, adds up each customer's order amounts; this is where the alias total is born.

  3. Lines 6-7FROM totals

    The outer query reads the CTE like a normal table, where total is now an ordinary existing column.

  4. Line 8WHERE total >= 1000

    The filter that failed before now works. Because it is >=, Chit Su with exactly 1000.00 is included, while Bo Bo with 300.00 is not.

  5. Line 9ORDER BY total DESC, customer_id;

    Largest first, with customer_id as a tiebreaker so the order is always stable.

You should see
 customer_id |  total
-------------+---------
           4 | 2500.00
           1 | 1150.00
           3 | 1000.00
(3 rows)

Scalar, IN and correlated subqueries in practice

The three queries below run on the same data. In the first, the average order is 825.00, so only order 106 (2500.00) beats it. The second returns customers who placed at least one order of 600 or more: Aye Aye, Chit Su and Daw Hla. The third is a correlated subquery that picks each customer's largest order: 101, 103, 104 and 106.

subquery_kinds.sql
-- scalar: compare with one computed value
SELECT order_id, amount
FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders);

-- list: membership test with IN
SELECT customer_name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE amount >= 600)
ORDER BY customer_name;

-- correlated: o2 is filtered by the current outer row o
SELECT o.order_id, o.customer_id, o.amount
FROM orders AS o
WHERE o.amount = (
  SELECT MAX(o2.amount) FROM orders AS o2 WHERE o2.customer_id = o.customer_id
)
ORDER BY o.order_id;

Chaining several CTEs

CTEs shine when you build a result one step at a time. totals computes each customer's sum, big_spenders filters totals, and the final SELECT joins customers to add names. Result: Daw Hla 2500.00, Aye Aye 1150.00, Chit Su 1000.00. When a step looks wrong, you can debug it on its own by ending the query with SELECT * FROM totals.

chained_ctes.sql
WITH totals AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  GROUP BY customer_id
), big_spenders AS (
  SELECT customer_id, total FROM totals WHERE total >= 1000
)
SELECT c.customer_name, b.total
FROM big_spenders AS b
JOIN customers AS c ON c.customer_id = b.customer_id
ORDER BY b.total DESC;

WITH RECURSIVE

A WITH RECURSIVE CTE refers to itself and can walk hierarchies such as category trees or org charts. PostgreSQL, SQLite and MySQL 8 support it, and SQL Server does too, without the RECURSIVE keyword. Once basic CTEs feel natural, continue with the WITH Queries page of the PostgreSQL docs.

In real projects

Where this shows up in real projects

Analytics queries are often long chains of CTEs: this month's orders, then totals per customer, then a comparison with last month, then the top ten. Data tools such as dbt recommend writing each model as a sequence of CTEs in their style guides, so a reviewer can understand every step on its own.

Application code is full of subqueries too. "Posts from accounts the current user follows" is WHERE author_id IN (SELECT followed_id FROM follows WHERE follower_id = $1). "Wishlisted products that are back in stock" is an EXISTS. Cleanup scripts remove duplicates with DELETE ... WHERE id IN (SELECT ...); run the subquery on its own as a SELECT first, to see exactly which rows will be deleted.

Common mistakes

Common mistakes

1. A scalar subquery that returns several rows

SELECT customer_name, (SELECT amount FROM orders WHERE orders.customer_id = customers.customer_id) fails with "more than one row returned by a subquery used as an expression" as soon as it reaches Aye Aye, who has two orders. If every customer in your test data has a single order, you only find the bug in production. Wrap the column in an aggregate such as MAX(amount) or SUM(amount) to guarantee one value.

2. Correlating on the wrong alias

When orders appears both outside and inside, an unaliased WHERE customer_id = customer_id compares the inner table with itself and is always true. No error appears; the subquery simply computes the MAX over every customer. Give the two copies distinct aliases such as o and o2, and write o2.customer_id = o.customer_id.

3. Using a CTE in the next statement

Following WITH totals AS (...) SELECT ...; with another SELECT * FROM totals; fails with "relation totals does not exist". A CTE exists for a single statement only. If you need it repeatedly, create a VIEW or a temporary table instead.

Mini challenge

Mini challenge: products above their category average

The products table holds seven products in three categories. Write two queries: the first finds products priced above the overall average, the second finds products priced above their own category's average.

  • Query 1: compare with the overall average using a scalar subquery
  • Query 2: compute each category's average in a CTE called category_avgs
  • Query 2: join the CTE to products and keep only rows above their average
  • Query 2: show name, category, price and category_avg (2 decimals), sorted by category
above_average.sql
-- Query 1: above the overall average
SELECT name, price
-- TODO: FROM products, keep prices above a scalar subquery (overall AVG)
-- TODO: sort by price, highest first

-- Query 2: above their own category's average
WITH category_avgs AS (
  -- TODO: one row per category with its average price
)
SELECT -- TODO: name, category, price, rounded category_avg
-- TODO: products joined to category_avgs on category
-- TODO: keep prices above the average, sort by category
;

Expected: Query 1: Backpack 39.00, Desk Lamp 24.00, Tote Bag 15.00. Query 2: name | category | price | category_avg -----------+------------+-------+-------------- Backpack | bags | 39.00 | 27.00 Desk Lamp | home | 24.00 | 16.00 Planner | stationery | 12.00 | 5.67 (3 rows)

Show hint

Inside the CTE write SELECT category, AVG(price) AS avg_price FROM products GROUP BY category. In the outer query, JOIN category_avgs AS a ON a.category = p.category, then filter WHERE p.price > a.avg_price. Query 1's average is about 14.71, leaving Backpack, Desk Lamp and Tote Bag.

Show solution
above_average.sql
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;

WITH category_avgs AS (
  SELECT category, AVG(price) AS avg_price
  FROM products
  GROUP BY category
)
SELECT p.name, p.category, p.price, ROUND(a.avg_price, 2) AS category_avg
FROM products AS p
JOIN category_avgs AS a ON a.category = p.category
WHERE p.price > a.avg_price
ORDER BY p.category;

Quick quiz 1 / 3

One customer has two orders. What happens with SELECT name, (SELECT amount FROM orders o WHERE o.customer_id = c.id) FROM customers c;?

Quick quiz 2 / 3

After running WITH t AS (SELECT 1 AS x) SELECT x FROM t;, you run SELECT x FROM t; on its own. What happens?

Quick quiz 3 / 3

With FROM orders AS o ... WHERE o.amount = (subquery), you want each customer's largest order. What must the subquery compute?

What to remember

  • The shape of a subquery's result, value, list or table, decides where it can be used.
  • WHERE cannot see aggregates or SELECT aliases, so compute them first in a CTE or derived table.
  • A correlated subquery refers to the outer row, so give the inner and outer copies distinct aliases.
  • Chain CTEs to make a query read step by step; each one lives for a single statement.

WITH Queries (Common Table Expressions) — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.