Sub topic 10
How the database runs these queries and which indexes help
This chapter explains how a database executes correlated subqueries, EXISTS, and NOT EXISTS, and which indexes make them fast. It assumes you can write EXISTS and NOT EXISTS queries, know INNER JOIN and LEFT JOIN, and can read a basic query plan. The examples use the customers, orders, order_items, and products tables from earlier chapters. Details differ between PostgreSQL, MySQL, SQL Server, and Oracle, so check your own engine's plan output.
The logical model versus the physical plan
The SQL you write describes a result, not a procedure. A correlated subquery reads as a loop: for each outer row, run the inner query with that row's values. This is the logical model, and it is the easiest way to reason about what a query means.
The optimizer is free to run something different, as long as the result is the same. It may do the loop literally, or it may rewrite the query into a join. This chapter separates two questions:
- What does the query mean? Use the loop model.
- How fast does it run? Read the plan.
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);Logically, for each customer the database asks: is there at least one order with this customer_id? If yes, the customer is returned.
Two physical strategies
Most engines run this query in one of two ways.
Strategy 1: nested loop with early exit
The database reads a customer, then probes orders for that customer's key. For EXISTS, the probe stops at the first matching order. This early exit is why EXISTS is cheap for customers with many orders: finding one match is enough.
The probe is fast only if the database can find a customer's orders without reading the whole table. With an index on orders (customer_id), each probe is a few index page reads. Without one, each probe is a full scan of orders. With 10,000 customers and 1,000,000 orders, that is roughly 10 billion row visits.
Strategy 2: semi-join
Many optimizers recognize EXISTS as a semi-join: return a row from the left side if at least one match exists on the right side, and never return a left row more than once. The optimizer can then pick a join algorithm:
- Nested loop semi-join. For each outer row, probe the inner side and stop at the first match. This works well when the outer side is small and the inner side has an index.
- Hash semi-join. Build a hash table of the inner side's
customer_idvalues, then scan the outer side and test each row against the table. This works well for large inputs with no useful index. - Merge semi-join. If both sides are sorted on the key (for example, from indexes), walk them together.
The same applies to NOT EXISTS, which becomes an anti-join: return a left row only if no match exists on the right.
The diagram below summarizes the choice the optimizer makes.
Reading the plan
Ask the database to show the plan. In PostgreSQL:
EXPLAIN ANALYZE
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);Look for these node names in PostgreSQL output:
| Plan node | Meaning |
|---|---|
| `Nested Loop Semi Join` | `EXISTS` run as a loop that stops at the first match |
| `Hash Semi Join` | `EXISTS` run by hashing the inner side |
| `Nested Loop Anti Join` / `Hash Anti Join` | `NOT EXISTS` run as an anti-join |
| `SubPlan` | The subquery was kept as a per-row check and was not turned into a join |
| `Seq Scan on orders` inside a loop | The probe has no index, so each outer row scans the table |
Other engines use different names. SQL Server shows Left Semi Join and Left Anti Semi Join. MySQL 8 shows semijoin strategies in EXPLAIN FORMAT=TREE. Oracle shows HASH JOIN SEMI and HASH JOIN ANTI.
Compare the estimated row counts with the actual ones. A large gap usually means stale statistics, which can lead the optimizer to choose a poor strategy. Running ANALYZE (PostgreSQL) or the equivalent statistics update on the tables is the first fix to try.
Which indexes help
The rule is simple: index the columns the inner query uses to find rows, which are the correlation columns.
CREATE INDEX idx_orders_customer_id ON orders (customer_id);This index serves several queries from earlier chapters:
EXISTSandNOT EXISTSonorders.customer_id = c.customer_id.- The correlated aggregate that compares each order to its customer's average total.
- The scalar subquery returning the customer's last order date.
- The
JOINandLEFT JOINrewrites.
Foreign key columns are the usual candidates. Some databases do not create an index on a foreign key automatically. PostgreSQL does not, and MySQL's InnoDB does. Check rather than assume.
Composite indexes
If the inner query has extra conditions, a composite index can cover them. Suppose you only care about customers with a recent order:
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= DATE '2026-01-01'
);An index on (customer_id, order_date) lets the database find the customer's orders and check the date inside the index. Put the equality column (the correlation column) first and the range column second.
CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date);The same index also answers MAX(o.order_date) for a customer efficiently, because the largest date for a given customer_id is at one end of that key range. Many engines can read just that one index entry.
Covering indexes and the SELECT list
The SELECT 1 inside EXISTS asks for no columns, so an index that contains all the columns used in the WHERE of the inner query can answer the check without touching the table at all. This is called an index-only scan. It is one more reason the select list does not matter: the engine never builds the returned values.
The double NOT EXISTS case
For the "ordered every product" query, the innermost query filters on o.customer_id, oi.product_id, and joins through order_id. Useful indexes are:
CREATE INDEX idx_orders_customer_order ON orders (customer_id, order_id);
CREATE INDEX idx_order_items_order_product ON order_items (order_id, product_id);This query is still expensive. It runs roughly once per customer-product pair, so cost grows with customers × products. Index it, and test it on realistic data before using it in production.
When the optimizer picks a bad plan
Missing index with a nested loop
The most common failure is a nested loop over a large inner table with no index. The plan shows a Seq Scan inside the loop and the query slows sharply as tables grow. Fix: add the index.
Low selectivity
An index helps when it narrows down to a small part of the table. If orders.status has only three values, an index on it alone barely helps, and the optimizer will often ignore it. Correlation columns such as customer_id usually have many distinct values, so they work well.
Expressions on the correlation column
Wrapping the column in a function can stop the index from being used:
-- The index on orders (customer_id) cannot be used for this condition
WHERE CAST(o.customer_id AS VARCHAR(20)) = CAST(c.customer_id AS VARCHAR(20))Keep the correlation columns the same type on both sides, and compare them directly. A type mismatch (for example, integer against text) can force an implicit conversion and has the same effect.
Correlated scalar subqueries in the SELECT list
This query runs its subquery once per customer:
SELECT c.customer_id, c.name,
(SELECT MAX(o.order_date)
FROM orders o
WHERE o.customer_id = c.customer_id) AS last_order_date
FROM customers c;With the index on orders (customer_id, order_date), each call is fast. Without it, each is a scan. Some optimizers can rewrite this into a grouped join, but many do not, so the index is the dependable fix. If the plan is still poor, rewrite it explicitly:
SELECT c.customer_id, c.name, lo.last_order_date
FROM customers c
LEFT JOIN (
SELECT customer_id, MAX(order_date) AS last_order_date
FROM orders
GROUP BY customer_id
) lo ON lo.customer_id = c.customer_id;This groups orders once, then joins. It is usually better when most customers are read, and the per-row version is usually better when the outer query is filtered down to a few customers.
EXISTS, IN, and JOIN in the optimizer
Modern optimizers treat EXISTS and IN with a subquery as the same semi-join in most cases, so the speed difference is often zero. Choose by readability and by correctness. The big exception is NOT IN, which has different NULL semantics from NOT EXISTS. Because the optimizer must preserve those semantics, it often cannot turn NOT IN into an anti-join, and the plan can be much slower. Prefer NOT EXISTS.
A JOIN rewrite is not free of risk. The join form of the EXISTS query needs DISTINCT to remove duplicates, and DISTINCT adds a sort or hash step that the semi-join avoids.
Measuring instead of guessing
- Run
EXPLAIN(orEXPLAIN ANALYZE) on the query. - Find the inner-table access. Is it an index scan or a full scan?
- Check that statistics are current.
- Add the index on the correlation columns, and run the plan again.
- Compare actual times on production-sized data, not on ten sample rows. Small tables hide every one of these problems.
Exercise
A query uses WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id). The plan shows a Seq Scan on orders inside a nested loop, and the query takes minutes on 2 million orders. What is the most likely fix, and what plan node would you expect to see afterwards?
Show answer
Create an index on orders (customer_id). Each probe then uses an index lookup instead of a full scan. The plan should show an index scan on orders inside a Nested Loop Anti Join, or a Hash Anti Join if the optimizer decides hashing is cheaper for the data size.
Exercise
You need customers who placed an order on or after 2026-01-01. Which composite index best supports the EXISTS query for this, and why does the column order matter?
Show answer
An index on (customer_id, order_date). The correlation column customer_id is an equality condition, so it goes first and narrows the search to one customer's entries. order_date is a range condition, so it goes second, and the database reads only the matching part of that customer's entries. With the order reversed, the index would be sorted by date first, and entries for one customer would be scattered across the range.