Sub topic 14
Performance considerations and reading query plans
This chapter assumes you can write scalar, IN, correlated, EXISTS, derived table, and CTE subqueries from the earlier chapters. It also assumes you are comfortable with joins and with how NULL behaves in comparisons. The examples use PostgreSQL syntax. MySQL 8 and other engines differ in details, and the text says so where it matters.
The working model: you describe, the optimizer decides
SQL is declarative. A subquery states what rows you want, not how to fetch them. The optimizer reads your statement, rewrites it into equivalent forms, estimates the cost of each, and picks a plan.
Two consequences follow:
- Two queries that look very different, such as an
INsubquery and a join, can produce the same plan. - Two queries that look almost identical can produce very different plans.
You cannot tell which case you are in by reading the SQL, so you read the plan. The usual workflow is shown below.
How subqueries are executed
Uncorrelated subqueries
An uncorrelated subquery does not refer to the outer query. Conceptually the database runs it once and reuses the result. A scalar subquery like (SELECT AVG(salary) FROM employees) becomes one computed value. An IN subquery becomes a set of values, often held in a hash table.
Most optimizers go further and turn IN (subquery) and EXISTS (subquery) into a semi-join. A semi-join keeps each outer row at most once if a match exists, and it never multiplies rows the way an ordinary join can.
Correlated subqueries
A correlated subquery depends on the current outer row. The naive model is a nested loop: for each outer row, run the inner query with that row's values. With 100,000 customers and an unindexed orders.customer_id, that means 100,000 scans of orders.
Real optimizers often avoid this. EXISTS and NOT EXISTS are usually converted to semi-joins and anti-joins. A correlated scalar subquery in the SELECT list is harder to rewrite, because it must return exactly one value, including a zero count, for every outer row. PostgreSQL commonly runs it as a repeated SubPlan.
The decisive fix is usually an index on the column the inner query filters by:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);With that index, each per-row probe is an index lookup instead of a table scan.
Reading a plan
EXPLAIN shows the plan the optimizer chose, with estimates only. EXPLAIN ANALYZE also runs the statement and reports actual rows and timings.
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
AND o.total > 100
);The output below is illustrative. Your costs, row counts, and node choices will differ.
Hash Semi Join (cost=310.20..520.45 rows=900 width=18) (actual time=3.1..6.8 rows=870 loops=1)
Hash Cond: (c.id = o.customer_id)
-> Seq Scan on customers c (cost=0.00..150.00 rows=10000 width=22) (actual time=0.01..1.2 rows=10000 loops=1)
-> Hash (cost=290.00..290.00 rows=1600 width=4) (actual time=3.0..3.0 rows=1500 loops=1)
-> Seq Scan on orders o (cost=0.00..290.00 rows=1600 width=4) (actual time=0.02..2.6 rows=1500 loops=1)
Filter: (total > 100)
Planning Time: 0.2 ms
Execution Time: 7.1 msRead a plan from the innermost, most indented nodes outward. The parts to look at:
| Plan element | What it tells you |
|---|---|
| `Hash Semi Join`, `Hash Anti Join` | The optimizer turned `IN`/`EXISTS` or `NOT EXISTS` into a join-like operation. This is usually the good outcome. |
| `SubPlan` or `Subquery Scan` | The subquery runs as its own step. Check its `loops` value. |
| `loops=N` | The node ran N times. Actual time and rows are per loop, so multiply to get the total. |
| `rows=` estimated vs actual | A large gap means stale or insufficient statistics, and the plan may be poorly chosen. |
| `Seq Scan` with a `Filter` | The table is read in full. This is fine for small tables or when most rows match, and a problem when few rows match. |
| `Index Scan`, `Index Only Scan` | An index is being used for lookup. |
Note that a Seq Scan is not automatically bad. If a query needs 80% of a table, scanning it sequentially beats jumping around through an index.
A safe pattern for the DELETE from earlier in this tutorial:
BEGIN;
EXPLAIN (ANALYZE)
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);
ROLLBACK;Where subqueries commonly get slow
Missing index on the correlated column
The most frequent cause. The inner query filters on orders.customer_id, and nothing indexes it, so every probe scans the whole table. The plan shows an inner node with a high loops count and a Seq Scan beneath it.
Correlated scalar subqueries in the SELECT list
Consider the order count per customer:
SELECT c.name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.id) AS order_count
FROM customers c;This can run one count per customer. With an index on orders.customer_id it is acceptable for modest tables. For large tables, aggregating once and joining is often faster, because the database groups orders in a single pass:
SELECT c.name, COALESCE(oc.order_count, 0) AS order_count
FROM customers c
LEFT JOIN (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) AS oc ON oc.customer_id = c.id;The LEFT JOIN keeps customers with no orders, and COALESCE turns their NULL count into 0. Both forms return the same rows. Which is faster depends on how many customers you actually need. If a WHERE or LIMIT reduces the outer rows to a handful, the correlated form can win, because it only computes counts for those rows.
NOT IN versus NOT EXISTS
Besides the NULL trap, NOT IN can be slower. PostgreSQL cannot turn NOT IN (subquery) into an anti-join, because it must preserve the NULL semantics. It typically falls back to a hashed SubPlan, and if that hash table does not fit in memory, it degrades to repeated scans. NOT EXISTS becomes a Hash Anti Join or an indexed anti-join. Prefer NOT EXISTS for both correctness and speed.
Duplicates and unnecessary DISTINCT
If you rewrite an IN subquery as a join, a customer with five matching orders appears five times. Adding DISTINCT fixes the output but adds a sort or hash step. The IN or EXISTS form avoids the duplicates, so use it when you only need to test whether a match exists.
Stale statistics
The optimizer chooses plans from table statistics. After a large load or delete, they can be badly wrong, and the plan shows estimated rows far from actual rows. Refresh them:
ANALYZE orders;CTEs and derived tables
Whether a CTE costs extra depends on the engine and version:
- PostgreSQL 12 and later inline a non-recursive CTE that is referenced once and has no side effects. It then plans like a derived table. Earlier versions always materialized it, which acted as an optimization barrier.
- A CTE referenced more than once is materialized by default in PostgreSQL, so it is computed once and reused.
- MySQL 8 merges derived tables and CTEs into the outer query when it can, and otherwise materializes them.
PostgreSQL lets you override the default:
WITH dept_avg AS MATERIALIZED (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT e.name, e.salary, da.avg_salary
FROM employees e
JOIN dept_avg da ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;Use MATERIALIZED when an expensive CTE is reused and you want it computed once. Use NOT MATERIALIZED when inlining lets the outer filter push down into the CTE. Neither keyword is portable, so check your engine's documentation.
Lateral subqueries and LIMIT
A lateral subquery runs once per outer row by design. That is efficient when the inner query uses an index and a small LIMIT, such as the largest order per customer. It is expensive when the inner query scans a large table each time. The same advice applies: index the correlating column, and for the "largest order" case an index on (customer_id, total DESC) lets each probe read a single entry.
A short checklist
- Run
EXPLAIN ANALYZEon a realistic data volume. Plans on tiny test tables are misleading. - Check estimated against actual rows.
- Look for
loopsvalues that are much greater than 1 on expensive nodes. - Index the columns used in correlated predicates and join conditions.
- Prefer
EXISTS/NOT EXISTSoverIN/NOT INwhenNULLis possible. - Change one thing at a time and measure again.
Exercise
A query lists customers with the count of their orders, using a correlated scalar subquery in the SELECT list. EXPLAIN ANALYZE shows a SubPlan node with loops=50000 and a Seq Scan on orders beneath it. Name two changes that could fix this, and say what you would check afterwards.
Show answer
One fix is to create an index on orders(customerid), so each of the 50,000 probes becomes an index lookup instead of a full table scan. The other is to rewrite the query to aggregate orders once in a derived table (SELECT customerid, COUNT(*) ... GROUP BY customer_id) and LEFT JOIN it to customers, using COALESCE(count, 0) so customers with no orders show 0. Afterwards, run EXPLAIN ANALYZE again and compare execution time and the loops count, and confirm the results are identical, including the customers with zero orders.
Exercise
Why is running EXPLAIN ANALYZE on a DELETE statement risky, and how do you do it safely?
Show answer
EXPLAIN ANALYZE actually executes the statement, so the DELETE removes real rows. Wrap it in a transaction: BEGIN; EXPLAIN ANALYZE DELETE ...; ROLLBACK; so the plan and timings are reported but the deletion is undone.