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”.
Subqueries: a query inside a query
Section titled “Subqueries: a query inside a query”A subquery is a SELECT in brackets inside another query. Three places are common:
| Where | Returns | Example |
|---|---|---|
in WHERE or SELECT | one value | price > (SELECT AVG(price) FROM …) |
after IN or EXISTS | rows to test against | id IN (SELECT merchant_id FROM advances) |
in FROM | a table | FROM (SELECT … GROUP BY …) AS per_product |
Paid transactions above the average paid price:
SELECT COUNT(*) AS above_averageFROM transactionsWHERE 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.
CTE: named steps
Section titled “CTE: named steps”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_purchasesFROM per_customer;| customers | repeat_customers | avg_purchases |
|---|---|---|
| 432 | 23 | 1.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
SELECTalias; - 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.
EXISTS: at least one such row
Section titled “EXISTS: at least one such row”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_advanceFROM merchants mWHERE 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.nameFROM products pWHERE 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_id | name |
|---|---|
| prd_18 | Product 18 |
| prd_20 | Product 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.nameFROM products pLEFT 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 NULLORDER 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.
Why not NOT IN
Section titled “Why not NOT IN”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.
| Form | A NULL in the subquery | Reads as |
|---|---|---|
NOT EXISTS (…) | safe | “there is no such row” |
LEFT JOIN … WHERE r.key IS NULL | safe | “the match is missing” |
NOT IN (SELECT …) | the result is empty | “not in the list” |
Practice
Section titled “Practice”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 customerchannel— 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 columnrefunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| customer_id | channel | is_trial | start_time | refunded_at | is_test |
|---|---|---|---|---|---|
| cus_00001 | south_market | false | 2025-10-12 16:30:29 | NULL | false |
| cus_00002 | south_market | false | 2025-06-25 19:26:50 | NULL | false |
| cus_00040 | north_market | false | 2025-09-13 17:45:04 | 2025-09-20 20:52:05 | false |
"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 transactionsFROM transactions tWHERE 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 |
“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.
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)
| id | name |
|---|---|
| mer_01 | Pocket Quest |
| mer_02 | Lumen Labs |
| mer_03 | Driftwood 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.nameFROM merchants mWHERE NOT EXISTS (SELECT 1 FROM advances v WHERE v.merchant_id = m.id)ORDER BY m.id;Expected output
| id | name |
|---|---|
| mer_02 | Lumen Labs |
| mer_05 | Maple Games |
| mer_06 | Orbit Fitness |
| mer_08 | Brightleaf |
| mer_10 | Paper Fox |
| mer_12 | Kite Works |
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.
Further reading
Section titled “Further reading”- WITH queries (common table expressions) — named steps, and when a CTE is folded into the main query.
- Subquery expressions —
EXISTS,INandNOT IN. - Scalar subqueries — a subquery used as one value.
- Subqueries in FROM — a subquery used as a table.
Related topics
Section titled “Related topics”- Row multiplication — why you aggregate in a CTE before a join.
- Top N per group — a CTE with
ROW_NUMBER()andWHERE rn = 1outside. - Cohorts and retention —
EXISTSfor “paid again in the next month”. - NULL logic — the
NOT INproblem in detail. - LEFT JOIN and zeros — the
LEFT JOINside of the anti-join.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.