how subqueries get planned
pull-up, semi joins, hashed SubPlans, and why IN and EXISTS often end up as the same plan.
- address
- everything.optimizer.subquery_planning
- part
- part 10, the optimizer
- chapter
- chapter 7 of 10
- reading time
- 8 min
a subquery in your SQL is rarely a subquery in the plan. the planner pulls up subqueries in FROM into the outer query, turns IN and EXISTS into semi joins (which is why they usually get the same plan), and NOT EXISTS into an anti join.
what it can't flatten stays a SubPlan: a little plan run for the outer query. NOT IN is the famous one, and how fast it is depends on whether its result fits in a hash table.
the picture
you know the advice "use EXISTS, not IN, it's faster"? in postgres it's usually the same plan. the planner rewrites both into the same thing before it costs anything.
think of an editor handed a sentence with a nested clause: "customers who are among the people who placed refunded orders". before typesetting, they rewrite it flat: "customers matched against refunded orders, each customer once". the meaning is the same; the flat version is just easier to work with. postgres does that rewrite on the query tree, right after parsing (the query's lifecycle).
- 1SELECT count(*) FROM customers
- 2WHERE id IN (SELECT customer_id FROM orders WHERE status = 'refunded');
| countint8 |
|---|
| 97 |
IN becomes a semi join: the refunded orders' customer ids are de-duplicated, then joined to customers.
pull-up
the simplest rewrite: a subquery in FROM (a derived table, subqueries) is merged into the outer query, so its tables join the outer ones and its WHERE merges with the outer WHERE:
EXPLAIN (COSTS OFF)
SELECT *
FROM (SELECT id, name, city FROM customers WHERE country = 'FR') AS fr
WHERE city = 'Paris'
ORDER BY id;one scan, both conditions on it. no trace of the subquery. pulled-up tables also join the outer query's list for join ordering, up to from_collapse_limit.
a subquery can't be pulled up when merging would change its meaning: it has LIMIT or OFFSET, aggregates or GROUP BY (those can sometimes still have conditions pushed into them), DISTINCT, window functions, set operations, or volatile functions in its output.
IN and EXISTS become semi joins
a semi join returns each outer row at most once if it has a match (EXISTS, semi and anti joins). IN (SELECT …) and a correlated EXISTS (SELECT …) both mean exactly that, so both get converted, and then the planner costs every way to run a semi join like any other join: a Semi Join node, or de-duplicating the inner side and doing a plain join (what you see above), with hash, merge or nested loop under it.
EXPLAIN (COSTS OFF)
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE status = 'refunded')
ORDER BY id;a subquery that can't be converted stays a SubPlan. IN under an OR is the common case, since a semi join can't express "this or that":
EXPLAIN (COSTS OFF)
SELECT name FROM customers AS c
WHERE c.id IN (SELECT o.customer_id FROM orders AS o WHERE o.status = 'refunded')
OR c.city = 'Paris'
ORDER BY id;hashed SubPlan 1: the subquery runs once, its result goes into a hash table, and each customer probes it. fine when the result fits in work_mem.
NOT IN, NOT EXISTS, and the hash table
NOT EXISTS becomes an anti join: outer rows with no match. NOT IN can't, because of NULL: if the subquery returns a single NULL, x NOT IN (…) is never true, which an anti join doesn't model. (the NOT IN trap has the wrong-answer half of that story.) so NOT IN is always a SubPlan, and work_mem decides which kind:
- 1SELECT count(*) FROM customers
- 2WHERE id NOT IN (SELECT customer_id FROM orders);
| countint8 |
|---|
| 38 |
NOT IN can't become an anti join (a NULL in the subquery would change the answer), so it stays a SubPlan: hashed, built once.
notice the estimate on NOT IN's scan, too: 1,000 customers for a real 38. the planner can't see into a SubPlan filter, so it guesses half the table.
the plain SubPlan is quadratic: for each of 2,000 customers, rescan the materialized orders until a match turns up (or doesn't). on these sizes it's still quick. on a million customers and ten million orders it's the query that never finishes, and it's why "NOT IN is slow" became folklore. the fix is to write NOT EXISTS, which is also the one that's correct with NULLs.
SELECT count(*) FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);SubPlans and InitPlans
a subquery that stays a subquery shows up in EXPLAIN under its parent node:
- an InitPlan doesn't depend on the outer row, so it runs once, before its parent needs it.
WHERE id = (SELECT max(…) FROM …)is one. - a SubPlan depends on the outer row (it's correlated), so it runs once per outer row. a scalar subquery in the SELECT list is the usual case:
EXPLAIN (COSTS OFF)
SELECT name FROM customers
WHERE id = (SELECT customer_id FROM orders ORDER BY ordered_at DESC LIMIT 1);the InitPlan finds the most recent order's customer once, and the index scan uses its result like a constant ((InitPlan 1).col1).
CTEs: inlined unless you say otherwise
since postgres 12, a non-recursive CTE that's referenced once, has no side effects and isn't marked MATERIALIZED is inlined like a subquery in FROM, and pulled up the same way (CTEs):
- 1WITH fr AS (SELECT id, name, city FROM customers WHERE country = 'FR')
- 2SELECT count(*) FROM fr WHERE city = 'Paris';
| countint8 |
|---|
| 66 |
a CTE used once is inlined: both conditions end up on one scan of customers.
before 12, every CTE was materialized, and people used them on purpose as an optimization fence. MATERIALIZED keeps that behaviour when you want it: to compute an expensive CTE once when it's referenced twice, or to stop the planner from pushing a condition in.
keylines
- subqueries in FROM are pulled up into the outer query when that can't change the result.
- IN and EXISTS become semi joins, so they usually share a plan.
- NOT EXISTS becomes an anti join. NOT IN stays a SubPlan: hashed if it fits in work_mem, a per-row rescan if not.
- InitPlan runs once; SubPlan runs once per outer row.
- CTEs referenced once are inlined since postgres 12. MATERIALIZED or OFFSET 0 make a fence.