Scrivio Interview library
InternalsIntermediate8 min read · updated 12 November 2026

How do PostgreSQL and MySQL execute EXISTS and NOT EXISTS subqueries? What plan nodes do you expect, and when can they be slow?

PostgreSQL pulls EXISTS and NOT EXISTS subqueries up into Semi Join and Anti Join nodes and runs them as a nested loop, hash or merge join. MySQL 8 rewrites EXISTS and IN into semi-joins executed with table pull-out, duplicate weedout, first match, loose scan or materialisation, and since 8.0.17 turns NOT EXISTS into an anti-join. They become slow mainly when the inner table has no index on the correlation column and a nested loop scans it once per outer row, or when stale statistics make the planner choose a nested loop where a hash join would be far cheaper; EXPLAIN ANALYZE shows the node and its loops count.

Why this question is asked

We write EXISTS because it says what we mean, but the database does not execute it the way it reads. Knowing what it does instead explains why the same query is fast on one table and takes minutes on another, and how to fix it without guessing. Interviewers ask this to see whether we can connect SQL to plans in two popular engines. In this answer, we will recap semi-joins and anti-joins, walk through what PostgreSQL does, then MySQL, look at the cases that go slow, and read a plan to confirm it.

1A Quick Recap of Semi-Joins and Anti-Joins

A semi-join returns each row of the outer table that has at least one match in the inner table, once, with no columns from the inner side. An anti-join returns each outer row that has no match. EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) is a semi-join of customers with orders, and NOT EXISTS is an anti-join.

The subquery is correlated, it refers to the outer row through c.id. Run literally, that would mean one subquery execution per customer. Both engines avoid that where they can by turning the subquery into a join, which opens up every join algorithm: a nested loop that probes an index per outer row, a hash join that builds a hash table once, or a merge join over two sorted inputs. The difference from a normal join is that the executor stops looking for more matches for an outer row as soon as it knows the answer.

2What PostgreSQL Does

When planning, PostgreSQL pulls up an EXISTS or NOT EXISTS in WHERE into the join tree as a semi-join or anti-join. The planner then costs the usual strategies and shows the result as Nested Loop Semi Join, Hash Semi Join, Merge Semi Join, or the Anti Join variants. With a hash, it can build the table on either side; recent versions can also build it on the outer side for anti joins, shown as a right anti join (check your version).

Java
EXPLAIN ANALYZE
SELECT c.id FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- Hash Anti Join (rows=180000) (actual rows=176412 loops=1)
-- Hash Cond: (c.id = o.customer_id)
-- -> Seq Scan on customers c (actual rows=1000000 loops=1)
-- -> Hash (actual rows=50000000 loops=1)
-- -> Seq Scan on orders o (actual rows=50000000 loops=1)

Notice that each node runs once, loops=1, so there is no per-row subquery. A nested loop version would look different: an Index Only Scan on orders under a Nested Loop Anti Join, with loops equal to the number of customers, each loop reading at most one index entry because the executor stops at the first match. When the outer side is small, that is the cheapest plan; for one million customers against fifty million orders, the hash is usually better.

There is a catch: the pull-up only happens for EXISTS in WHERE combined with AND, and for IN with a subquery. A NOT IN subquery is not turned into an anti-join, because its NULL semantics differ, so PostgreSQL runs it as a SubPlan, hashed if the result fits in memory and row by row otherwise. An EXISTS hidden inside an OR, or in the select list, also stays a SubPlan and runs per outer row.

3What MySQL 8 Does

MySQL's optimizer converts IN and EXISTS subqueries into semi-joins and then picks one of several strategies. Table pull-out turns the subquery into a plain join when the inner side is unique on the join key, such as a primary key. First match joins as usual but stops at the first matching inner row for each outer row. Loose scan reads an index on the inner side and takes only the first entry of each key value. Duplicate weedout runs a normal join and removes repeated outer rows using a temporary table. Materialisation runs the subquery once into a temporary table with an index and joins against it.

For NOT EXISTS and NOT IN, MySQL 8.0.17 added the anti-join transformation, so these too become joins rather than per-row subqueries. Since 8.0.18 the hash join is available as well, so an anti-join can be executed as a hash anti-join. EXPLAIN FORMAT=TREE or EXPLAIN ANALYZE shows the chosen form, for example a nested loop antijoin, and the classic EXPLAIN shows strategies in the Extra column, such as FirstMatch or Start temporary and End temporary for duplicate weedout.

How each engine runs EXISTS
PostgreSQLMySQL 8
EXISTS / INSemi Join node: nested loop, hash or mergeSemi-join: pull-out, first match, loose scan, weedout, materialise
NOT EXISTSAnti Join nodeAnti-join since 8.0.17
NOT INSubPlan (hashed or per row)Anti-join with NULL handling
See it withEXPLAIN (ANALYZE, BUFFERS)EXPLAIN ANALYZE, FORMAT=TREE

4When These Plans Get Slow

The most common slow case is a nested loop whose inner side has no index on the correlation column. For each outer row, the executor scans the inner table until it finds a match. For EXISTS that may stop early, but for NOT EXISTS the answer for a customer without orders is only known after reading every row, so the scan runs to the end each time. One million outer rows times a 50-million-row scan is not going to finish. An index on orders(customer_id) turns each probe into a few page reads.

The second case is a bad estimate. If statistics are stale, for example after a bulk load, the planner may think the outer side has 100 rows when it has a million and choose a nested loop where a hash anti join would be far cheaper. Running ANALYZE on the tables, or raising the statistics target on a skewed column, usually fixes it. A third case is a hash that does not fit in work_mem and spills to disk in batches, which shows as Batches greater than 1 under the Hash node.

Java
-- The slow shape: inner side scanned once per outer row
-- Nested Loop Anti Join (actual time=0.1..412000 rows=176412 loops=1)
-- -> Seq Scan on customers c (actual rows=1000000 loops=1)
-- -> Seq Scan on orders o (actual rows=0 loops=1000000) <- a full scan per customer
-- Filter: (customer_id = c.id)
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;
-- now: Nested Loop Anti Join -> Index Only Scan using orders_customer_id_idx (loops=1000000, rows=1 each)
-- or a Hash Anti Join, whichever the planner costs lower

So the reading habit is simple: find the semi or anti join node, look at the inner side, and multiply its per-loop work by its loops count. That product is the real cost, and it tells us whether we need an index, fresher statistics or more memory.

5Follow-up questions

Why does the executor stop early for semi-joins but not always for anti-joins?

For a semi-join, one match proves the answer is yes, so it can stop. For an anti-join, a match proves the answer is no and it can also stop, which is fast for customers that do have orders. But for customers without orders, it must look at every possible match before concluding there are none. With an index, that is one probe that finds nothing; without one, it is a full scan. That is why NOT EXISTS needs the index even more than EXISTS.

Does LEFT JOIN ... WHERE inner.id IS NULL get the same plan as NOT EXISTS?

In PostgreSQL usually yes: the planner recognises the pattern and produces an Anti Join, as long as the column tested for NULL cannot be NULL in a matched row, such as a primary key. MySQL also optimises it, shown as Not exists in classic EXPLAIN. NOT EXISTS is still clearer, and it stays correct when more conditions are added, while the LEFT JOIN form breaks if someone filters on the inner table in WHERE.

What does Memoize mean under a nested loop semi join?

Memoize, available since PostgreSQL 14, caches inner-side results by the parameter value. If many outer rows share the same correlation value, the inner lookup runs once per distinct value instead of once per row. It shows hits and misses in EXPLAIN ANALYZE, and a high hit rate explains why a nested loop with many loops is still fast.

6Conclusion

In this answer, we saw that PostgreSQL turns EXISTS and NOT EXISTS into Semi Join and Anti Join nodes using nested loop, hash or merge strategies, while NOT IN stays a SubPlan, and that MySQL 8 uses semi-join strategies such as table pull-out, first match, loose scan, duplicate weedout and materialisation, with anti-joins since 8.0.17. These plans go slow when a nested loop scans an unindexed inner table per outer row or when stale statistics pick the wrong strategy, and EXPLAIN ANALYZE with its loops count shows which.

What to say in the interviewAbout 100 seconds aloud

Open with

Neither engine really runs a correlated EXISTS once per row if it can avoid it. PostgreSQL pulls EXISTS and IN subqueries into the join tree as a semi-join and NOT EXISTS as an anti-join, and the plan shows Nested Loop Semi Join, Hash Semi Join, Merge Anti Join and so on.

Then, if they want more

The executor stops at the first match for each outer row. NOT IN is the exception, it stays a SubPlan because of NULL semantics, hashed if it fits in memory.

MySQL 8 transforms IN and EXISTS into semi-joins and picks a strategy: table pull-out when the inner side is unique, first match, loose scan over an index, duplicate weedout with a temp table, or materialisation of the subquery. Since 8.0.17 it also turns NOT EXISTS and NOT IN into anti-joins, and since 8.0.18 it can execute them as hash joins.

These plans become slow in two typical ways. First, a nested loop where the inner table has no index on the correlation column, so it scans the inner table once per outer row; that is especially bad for NOT EXISTS, because rows without a match need the whole scan.

Second, stale or poor statistics, so the planner expects a few outer rows, picks a nested loop, and actually gets a million. To confirm, I run EXPLAIN ANALYZE, find the semi or anti join node, and multiply the inner side's work by its loops count. Usually the fix is an index on the correlation column or an ANALYZE.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8, MySQL 8.0, PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do PostgreSQL and MySQL execute EXISTS and NOT EXISTS subqueries? What plan nodes do...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/8daf0eb56a/