The symptom
A correlated subquery uses a value from the outer query, so in principle it has to be evaluated again for each outer row. Optimizers turn many of them into joins. When they cannot, the plan shows the subquery as a separate block that runs in a loop: SubPlan in PostgreSQL, DEPENDENT SUBQUERY in MySQL, CORRELATED SCALAR SUBQUERY in SQLite. The cost is the cost of one execution times the number of outer rows, which is easy to miss because the plan prints the subquery only once.
The query plan viewer flags subqueries that are executed per row. The examples use a shop schema with 20,000 customers and 400,000 orders, with no index on orders.customer_id to begin with.
Diagnose it
A subquery that runs once per outer row
This query counts the orders of 50 customers with a subquery in the select list:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.customer_id, c.email,
(SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers AS c
WHERE c.customer_id BETWEEN 100 AND 149;
Index Scan using customers_pkey on customers c (cost=0.29..474112.66 rows=50 width=33) (actual rows=50.00 loops=1)
Index Cond: ((customer_id >= 100) AND (customer_id <= 149))
SubPlan 1
-> Aggregate (cost=9482.06..9482.07 rows=1 width=8) (actual rows=1.00 loops=50)
-> Seq Scan on orders o (cost=0.00..9482.00 rows=23 width=0) (actual rows=18.00 loops=50)
Filter: (customer_id = c.customer_id)
Rows Removed by Filter: 399982
loops=50 on the nodes under SubPlan 1 is the repeat count, and the row counts next to it are per loop. Each loop scans all 400,000 orders, so the query reads 20 million rows to return 50.
EXPLAIN SELECT c.customer_id, c.email,
(SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers AS c
WHERE c.customer_id BETWEEN 100 AND 149\G
select_type: PRIMARY
table: c
type: range
key: PRIMARY
rows: 50
Extra: Using where
select_type: DEPENDENT SUBQUERY
table: o
type: ALL
key: NULL
rows: 398641
Extra: Using where
In MySQL, DEPENDENT SUBQUERY with type: ALL is the same thing: a full scan of orders for each of the 50 customers. A plain SUBQUERY without the word dependent runs once and is not a concern.
EXPLAIN QUERY PLAN
SELECT c.customer_id, c.email,
(SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers AS c
WHERE c.customer_id BETWEEN 100 AND 149;
|--SEARCH c USING INTEGER PRIMARY KEY (rowid>? AND rowid<?)
`--CORRELATED SCALAR SUBQUERY 1
`--SCAN o
EXPLAIN PLAN FOR
SELECT c.customer_id, c.email,
(SELECT count(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers c
WHERE c.customer_id BETWEEN 100 AND 149;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 51 | 1377 | 16897 (1)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL | ORDERS | 22 | 110 | 650 (1)| 00:00:01 |
| 3 | TABLE ACCESS BY INDEX ROWID BATCHED| CUSTOMERS | 51 | 1377 | 3 (0)| 00:00:01 |
|* 4 | INDEX RANGE SCAN | SYS_C008720 | 51 | | 2 (0)| 00:00:01 |
2 - filter("O"."CUSTOMER_ID"=:B1)
Oracle lists the subquery first, above the main query, and its filter compares the column with a bind placeholder, :B1, that is filled in for each outer row.
SQL Server rewrites this query into an outer join by itself and reads Orders once:
SET STATISTICS IO ON;
GO
SELECT c.CustomerId, c.Email,
(SELECT COUNT(*) FROM dbo.Orders AS o WHERE o.CustomerId = c.CustomerId) AS OrderCount
FROM dbo.Customers AS c
WHERE c.CustomerId BETWEEN 100 AND 149;
Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0
Table 'Customers'. Scan count 1, logical reads 2, physical reads 0
NOT IN over a column that allows NULL
NOT IN has to answer "unknown" when the subquery returns a NULL, so engines cannot treat it as a plain anti join unless the column is declared NOT NULL. To show it, add a table of referrals where referred_by is NULL for one customer in ten, then look for customers who never referred anyone:
CREATE TABLE referrals (customer_id int NOT NULL, referred_by int);
INSERT INTO referrals
SELECT g, CASE WHEN g % 10 = 0 THEN NULL ELSE g / 2 + 1 END
FROM generate_series(1, 20000) AS g;
ANALYZE referrals;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.customer_id
FROM customers AS c
WHERE c.customer_id NOT IN (SELECT r.referred_by FROM referrals AS r);
Seq Scan on customers c (cost=339.00..756.00 rows=10000 width=4) (actual rows=0.00 loops=1)
Filter: (NOT (ANY (customer_id = (hashed SubPlan 1).col1)))
Rows Removed by Filter: 20000
SubPlan 1
-> Seq Scan on referrals r (cost=0.00..289.00 rows=20000 width=4) (actual rows=20000.00 loops=1)
Two things are wrong. PostgreSQL does not plan NOT IN as a join: it evaluates a SubPlan as a filter, hashed if the subquery result fits in work_mem and rescanned for every outer row if it does not. And the query returns rows=0. Because the subquery result contains NULLs, no customer can be proven to be absent from it, so NOT IN returns nothing at all.
CREATE TABLE referrals (customer_id NUMBER NOT NULL, referred_by NUMBER);
INSERT INTO referrals
SELECT customer_id,
CASE WHEN MOD(customer_id, 10) = 0 THEN NULL ELSE TRUNC(customer_id / 2) + 1 END
FROM customers;
COMMIT;
EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'REFERRALS');
EXPLAIN PLAN FOR
SELECT c.customer_id
FROM customers c
WHERE c.customer_id NOT IN (SELECT r.referred_by FROM referrals r);
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 10001 | 90009 | 28 (0)| 00:00:01 |
|* 1 | HASH JOIN RIGHT ANTI NA| | 10001 | 90009 | 28 (0)| 00:00:01 |
| 2 | TABLE ACCESS FULL | REFERRALS | 20000 | 80000 | 13 (0)| 00:00:01 |
| 3 | INDEX FAST FULL SCAN | SYS_C008720 | 20000 | 97K| 15 (0)| 00:00:01 |
Oracle marks the null-aware version of the join with NA. SQL Server adds a second anti join to the plan whose only job is to look for a NULL in the subquery column.
Fix it
Rewrite the subquery as a join
A join with GROUP BY lets the engine read the inner table once, whatever the number of outer rows:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.customer_id, c.email, count(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.customer_id BETWEEN 100 AND 149
GROUP BY c.customer_id, c.email;
GroupAggregate (cost=9591.96..9599.96 rows=50 width=33) (actual rows=50.00 loops=1)
Group Key: c.customer_id
-> Sort (cost=9591.96..9594.46 rows=1000 width=29) (actual rows=905.00 loops=1)
Sort Key: c.customer_id
Sort Method: quicksort Memory: 67kB
-> Hash Right Join (cost=9.91..9542.14 rows=1000 width=29) (actual rows=905.00 loops=1)
Hash Cond: (o.customer_id = c.customer_id)
-> Seq Scan on orders o (cost=0.00..8482.00 rows=400000 width=8) (actual rows=400000.00 loops=1)
-> Hash (cost=9.29..9.29 rows=50 width=25) (actual rows=50.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 11kB
-> Index Scan using customers_pkey on customers c (cost=0.29..9.29 rows=50 width=25) (actual rows=50.00 loops=1)
Index Cond: ((customer_id >= 100) AND (customer_id <= 149))
Index Searches: 1
Use LEFT JOIN and count a column of the joined table so that customers with no orders still appear with a count of 0, as they did with the subquery. This is the better fix when the outer query returns many rows.
Index the correlated column
When the outer query returns few rows, running the subquery per row is fine as long as each run is an index lookup:
CREATE INDEX orders_customer_idx ON orders (customer_id);
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.customer_id, c.email,
(SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers AS c
WHERE c.customer_id BETWEEN 100 AND 149;
SubPlan 1
-> Aggregate (cost=4.88..4.89 rows=1 width=8) (actual rows=1.00 loops=50)
-> Index Only Scan using orders_customer_idx on orders o (cost=0.42..4.83 rows=23 width=0) (actual rows=18.00 loops=50)
Index Cond: (customer_id = c.customer_id)
CREATE INDEX orders_customer_idx ON orders (customer_id);
EXPLAIN SELECT c.customer_id, c.email,
(SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers AS c
WHERE c.customer_id BETWEEN 100 AND 149\G
select_type: PRIMARY
table: c
type: range
key: PRIMARY
rows: 50
Extra: Using where
select_type: DEPENDENT SUBQUERY
table: o
type: ref
key: orders_customer_idx
rows: 22
Extra: Using index
CREATE INDEX orders_customer_idx ON orders (customer_id);
EXPLAIN QUERY PLAN
SELECT c.customer_id, c.email,
(SELECT count(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers AS c
WHERE c.customer_id BETWEEN 100 AND 149;
|--SEARCH c USING INTEGER PRIMARY KEY (rowid>? AND rowid<?)
`--CORRELATED SCALAR SUBQUERY 1
`--SEARCH o USING COVERING INDEX orders_customer_idx (customer_id=?)
The subquery is still dependent, but each execution now reads about 20 index entries.
Replace NOT IN with NOT EXISTS
NOT EXISTS only asks whether a matching row exists, so NULLs in the subquery do not change the answer and the engine can use an ordinary anti join:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT c.customer_id
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM referrals AS r WHERE r.referred_by = c.customer_id);
Hash Right Anti Join (cost=617.00..1069.75 rows=10000 width=4) (actual rows=10000.00 loops=1)
Hash Cond: (r.referred_by = c.customer_id)
-> Seq Scan on referrals r (cost=0.00..289.00 rows=20000 width=4) (actual rows=20000.00 loops=1)
-> Hash (cost=367.00..367.00 rows=20000 width=4) (actual rows=20000.00 loops=1)
Buckets: 32768 Batches: 1 Memory Usage: 960kB
-> Seq Scan on customers c (cost=0.00..367.00 rows=20000 width=4) (actual rows=20000.00 loops=1)
EXPLAIN PLAN FOR
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM referrals r WHERE r.referred_by = c.customer_id);
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 10001 | 90009 | 28 (0)| 00:00:01 |
|* 1 | HASH JOIN RIGHT ANTI | | 10001 | 90009 | 28 (0)| 00:00:01 |
|* 2 | TABLE ACCESS FULL | REFERRALS | 18000 | 72000 | 13 (0)| 00:00:01 |
| 3 | INDEX FAST FULL SCAN| SYS_C008720 | 20000 | 97K| 15 (0)| 00:00:01 |
The plan is an anti join and the query now returns the 10,000 customers who referred nobody. If you must keep NOT IN, add WHERE referred_by IS NOT NULL inside the subquery, or declare the column NOT NULL when the data allows it.
When to leave it alone
A dependent subquery that runs a handful of times, or that does one index lookup per row for a few thousand rows, is not a problem. Neither is a subquery the plan marks as executed once: PostgreSQL calls it an InitPlan, MySQL a SUBQUERY without "dependent". Rewrite when the repeat count multiplied by the cost of one run is a large share of the query.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Find the subquery block in the plan and read how many times it ran.
- Multiply the rows one execution reads by that count.
- Check whether each execution uses an index on the correlated column.
- Rewrite as a join with GROUP BY when the outer query returns many rows.
- Add an index on the correlated column when it returns few.
- Replace NOT IN (subquery) with NOT EXISTS, or exclude NULLs in the subquery.
- Compare results before and after: NOT IN and NOT EXISTS differ when NULLs are present.
Questions that come up
What is a dependent subquery in MySQL EXPLAIN?
It is a subquery that refers to a column of the outer query, so MySQL evaluates it again for each outer row. The select_type column shows DEPENDENT SUBQUERY. It is cheap when each evaluation is an index lookup and expensive when each one scans a table.
Are correlated subqueries always slow?
No. Optimizers convert many of them into joins, and one that stays correlated is fine when it runs few times or uses an index each time. It is slow when a scan is repeated for thousands of outer rows.
Why does NOT IN return no rows?
If the subquery returns even one NULL, the comparison with that NULL is unknown for every outer row, so no row can satisfy NOT IN and the result is empty. NOT EXISTS does not have this behavior, and neither does NOT IN once NULLs are filtered out of the subquery.
Is NOT EXISTS faster than NOT IN?
When the subquery column allows NULL, usually yes, because NOT EXISTS can be executed as a plain anti join while NOT IN needs null-aware handling. When the column is declared NOT NULL, most engines produce the same plan for both. PostgreSQL is the exception: it does not turn NOT IN into an anti join, so NOT EXISTS is the safer form there.
Should I use a join or a subquery?
Write whichever is clearer and check the plan. If the plan shows the subquery being executed per row at volume, rewrite it as a join with GROUP BY or as EXISTS. If the optimizer has already turned it into a join, there is nothing to gain from rewriting.