Skip to content

Subqueries and CTE

Many tasks take two steps: aggregate first, then filter or count the aggregates. A CTE gives each step a name and lets you run it on its own. EXISTS answers “has at least one such row” without multiplying rows, and NOT EXISTS answers “never”.

A subquery is a SELECT in brackets inside another query. Three places are common:

WhereReturnsExample
in WHERE or SELECTone valueprice > (SELECT AVG(price) FROM …)
after IN or EXISTSrows to test againstid IN (SELECT merchant_id FROM advances)
in FROMa tableFROM (SELECT … GROUP BY …) AS per_product

Paid transactions above the average paid price:

SELECT COUNT(*) AS above_average
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
AND charged_usd > (
SELECT AVG(charged_usd)
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
);
above_average
1185

The inner query returns one value, the average of 14.91, and the outer query compares every row with it. A subquery used as a value must return one row. With more rows, the query fails: more than one row returned by a subquery used as an expression.

WITH name AS (…) defines a step that the next steps read like a table. It does the same job as a subquery in FROM, but it reads from top to bottom, and each step has a name.

The typical case is an aggregate of aggregates. “How many customers paid more than once in August?” needs the purchases per customer first, then a count over customers:

WITH per_customer AS (
SELECT customer_id, COUNT(*) AS purchases
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
AND start_time >= TIMESTAMP '2026-08-01'
AND start_time < TIMESTAMP '2026-09-01'
GROUP BY customer_id
)
SELECT COUNT(*) AS customers,
COUNT(*) FILTER (WHERE purchases > 1) AS repeat_customers,
ROUND(AVG(purchases), 2) AS avg_purchases
FROM per_customer;
customersrepeat_customersavg_purchases
432231.12

COUNT(*) in the outer query counts customers, because each row of per_customer is one customer. AVG(purchases) is an average of counts. Neither is possible in a single GROUP BY.

A step is needed for:

  • a filter on a SELECT alias;
  • an aggregate of an aggregate, as above;
  • a filter on a window function, such as WHERE rn = 1 (see Top N per group);
  • two “many” tables, each aggregated to one row per key before the join (see LEFT JOIN and zeros).

Work in small steps. Write the first CTE, finish the query with SELECT * FROM per_customer LIMIT 5, run it and look at the rows. Only then write the next step. A CTE that is used once costs nothing extra: PostgreSQL folds it into the main query.

Some conditions are about other rows: “customers who also had a refund”, “merchants with at least one advance”. Words to listen for: also, at least one, ever, any. EXISTS (subquery) is true when the subquery returns at least one row. What the subquery selects does not matter, so it is written SELECT 1.

SELECT COUNT(*) AS merchants_with_advance
FROM merchants m
WHERE EXISTS (
SELECT 1
FROM advances v
WHERE v.merchant_id = m.id
);
merchants_with_advance
6

The line v.merchant_id = m.id links the subquery to the outer row. The subquery is checked for each merchant, and the answer is true or false, so each merchant counts once. A JOIN would return one row per advance: 38 rows for the same six merchants.

Without the link, EXISTS is true for every row as soon as the table has any rows: the same query without WHERE v.merchant_id = m.id returns 12. A result of 100% is a reason to check the link.

For the positive case, IN (SELECT …) gives the same answer: WHERE m.id IN (SELECT merchant_id FROM advances) also returns 6. The negative form is where IN breaks.

“Never”: NOT EXISTS and LEFT JOIN … IS NULL

Section titled ““Never”: NOT EXISTS and LEFT JOIN … IS NULL”

An anti-join keeps the rows that have no match. Words to listen for: never, without, no …. Two forms are safe. Products with no web checkout sale in September, test purchases excluded:

SELECT p.id AS product_id, p.name
FROM products p
WHERE NOT EXISTS (
SELECT 1
FROM transactions t
WHERE t.product_id = p.id
AND t.channel = 'web'
AND NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-10-01'
)
ORDER BY p.id;
product_idname
prd_18Product 18
prd_20Product 20

The same with LEFT JOIN: keep the rows of NULLs, and only them. It returns the same two products.

SELECT p.id AS product_id, p.name
FROM products p
LEFT JOIN transactions t
ON t.product_id = p.id
AND t.channel = 'web'
AND NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-10-01'
WHERE t.transaction_id IS NULL
ORDER BY p.id;

Test IS NULL on a column that is never NULL in a real match, such as the key of the right table. All other conditions on the right table stay in ON.

NOT IN (SELECT …) looks like the shortest form. But if the subquery returns one NULL, the condition is never true, and the result is empty without an error. NULL logic shows it on the practice data. NOT EXISTS checks row by row, and a NULL does not affect it.

FormA NULL in the subqueryReads as
NOT EXISTS (…)safe“there is no such row”
LEFT JOIN … WHERE r.key IS NULLsafe“the match is missing”
NOT IN (SELECT …)the result is empty“not in the list”
SQLWrite a query

How many paid transactions in September 2026 were made by customers who had at least one refund before 2026-09-01?

Output columns: transactions

Tables, columns and how they connect

transactions — one row = one paid (or trial) period of a subscription

  • customer_id — the customer
  • channel — north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)
  • is_trial — free trial (7 days, price 0)
  • start_time — start of the period = time of purchase; "started in …" means this column
  • refunded_at — when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULL
  • is_test — test purchase: exclude it from business numbers
customer_idchannelis_trialstart_timerefunded_atis_test
cus_00001south_marketfalse2025-10-12 16:30:29NULLfalse
cus_00002south_marketfalse2025-06-25 19:26:50NULLfalse
cus_00040north_marketfalse2025-09-13 17:45:042025-09-20 20:52:05false

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

SELECT COUNT(*) AS transactions
FROM transactions t
WHERE NOT t.is_trial AND NOT t.is_test AND t.channel <> 'promo'
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-10-01'
AND EXISTS (
SELECT 1 FROM transactions r
WHERE r.customer_id = t.customer_id
AND r.refunded_at < TIMESTAMP '2026-09-01'
);

Expected output

transactions
2
1 row

“Does the customer have at least one row of this kind” is EXISTS with a link to the same customer: r.customer_id = t.customer_id. A JOIN would multiply the rows if a customer had several refunds. The hidden data has such a customer, so Check catches it. IN (SELECT customer_id …) also works here.

SQLWrite a querycore

Which merchants never received an advance? Merchant id and name.

Output columns: id, nameOrder: ORDER BY id

Tables, columns and how they connect

merchants — merchants (12 rows): businesses that sell subscriptions on the platform

  • id — key: mer_01 …
  • name — company name (made up)
idname
mer_01Pocket Quest
mer_02Lumen Labs
mer_03Driftwood Labs

advances — advances: early payouts to merchants against marketplace payouts that have not arrived yet

  • merchant_id — → merchants.id
merchant_id
mer_01
mer_01
mer_01

Joins: advances.merchant_id = merchants.id

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

SELECT m.id, m.name
FROM merchants m
WHERE NOT EXISTS (SELECT 1 FROM advances v WHERE v.merchant_id = m.id)
ORDER BY m.id;

Expected output

idname
mer_02Lumen Labs
mer_05Maple Games
mer_06Orbit Fitness
mer_08Brightleaf
mer_10Paper Fox
mer_12Kite Works
6 rows

An anti-join: NOT EXISTS, or LEFT JOIN advances v … WHERE v.advance_id IS NULL. NOT IN is dangerous: one NULL in the subquery, and the result is empty. advances.merchant_id has no NULL here, so NOT IN returns the right rows and Check cannot catch it. It is still the habit to avoid.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.