Sub topic 9
Semi-joins, anti-joins, and rewriting with JOIN
This chapter assumes you can write INNER JOIN and LEFT JOIN, use DISTINCT and GROUP BY, and read EXISTS and NOT EXISTS queries. It also assumes you know that a comparison with NULL evaluates to UNKNOWN, not true. We use the same customers, orders, order_items, and products tables as in earlier chapters.
By the end you should be able to translate between EXISTS and join forms, and say when the two forms return different results.
Two kinds of join you do not write directly
A regular join combines columns from both tables. It returns one output row for each matching pair of rows. Two other operations exist in relational algebra, and SQL has no keyword for either of them:
- A semi-join returns the rows from the left table that have at least one match in the right table. It returns only the left table's columns, and each left row appears at most once.
- An anti-join returns the rows from the left table that have no match in the right table. It also returns only the left table's columns.
You already know how to write both. WHERE EXISTS (...) is a semi-join, and WHERE NOT EXISTS (...) is an anti-join. The word "join" is there because the database can run them with the same machinery it uses for joins, as the last section of this chapter explains.
The key property is that neither operation multiplies rows. A customer with 50 orders still appears once in a semi-join. That property is the reason the join rewrites below need extra care.
The semi-join as a join, and the duplicate-row risk
Here is the EXISTS form and a join form that looks equivalent:
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
SELECT c.customer_id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id;The second query is wrong for the question "which customers have at least one order". A customer with three orders appears three times, because the join produces one row per matching pair. The usual repair is DISTINCT:
SELECT DISTINCT c.customer_id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id;This returns the same set of customers as the EXISTS query, but it gets there differently. The database first builds every customer-order pair and then removes duplicates. For a customer with 10,000 orders, that is 10,000 rows produced and then collapsed into one. EXISTS can stop at the first matching order.
DISTINCT has a second cost. It applies to every selected column, not only to the customer key. If you add a column from orders to the select list, the duplicates no longer collapse, and the query silently starts answering a different question. The EXISTS form does not have this problem, because the orders columns are not reachable from the outer query.
| Aspect | `EXISTS` | `JOIN` with `DISTINCT` |
|---|---|---|
| Rows per customer | At most one, by definition | One per order, then collapsed |
| Work per customer | Can stop at the first match | Builds all matching pairs |
| Columns from `orders` in output | Not available | Available, but break `DISTINCT` |
| Intent visible in the SQL | Yes, "has at least one" | Hidden behind `DISTINCT` |
Use the join form when you actually need columns from the matched rows. Use EXISTS when you only need to know that a match exists.
The anti-join as a LEFT JOIN
The NOT EXISTS query finds customers with no orders:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);The equivalent join form is the LEFT JOIN ... IS NULL pattern:
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;A LEFT JOIN keeps every customer. When a customer has no matching order, the orders columns in that output row are filled with NULL. The WHERE clause then keeps only those rows. No DISTINCT is needed here, because a customer that survives the filter has exactly one output row: the one with the NULL-filled order columns.
Choosing the column in the IS NULL test
The test column must be one that can never be NULL in a real matching row. Otherwise a genuine match with a NULL in that column is mistaken for a missing match. The primary key of the right table is the safe choice, which is why the example tests o.order_id. The join column o.customer_id also works, because a row can only match if it equals c.customer_id, which is not NULL. A nullable column such as a shipped_date would give wrong answers.
Put the extra conditions in ON, not WHERE
Suppose you want customers who have no orders in 2026. With NOT EXISTS, the extra condition goes inside the subquery:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= DATE '2026-01-01'
AND o.order_date < DATE '2027-01-01'
);In the LEFT JOIN form the same conditions must go in the ON clause:
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND o.order_date >= DATE '2026-01-01'
AND o.order_date < DATE '2027-01-01'
WHERE o.order_id IS NULL;If you move the date conditions into WHERE, they run after the join. For a customer with no matching orders, o.order_date is NULL, the date comparison is UNKNOWN, and the row is discarded. The query then returns no rows at all, because WHERE o.order_id IS NULL and WHERE o.order_date >= ... cannot both hold. This is one of the most common mistakes when converting an anti-join, and the NOT EXISTS form avoids it because the subquery keeps its filters in one place.
Three ways to ask for absence
There are now three ways to find customers without orders: NOT EXISTS, LEFT JOIN ... IS NULL, and NOT IN. They return the same rows when the data is clean. They differ when NULL is present.
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders o
);
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);If orders.customer_id contains even one NULL, the NOT IN query returns no rows. For every customer, the comparison against that NULL is UNKNOWN, and NOT of UNKNOWN is still UNKNOWN, so no row passes the filter. The NOT EXISTS query is unaffected. Its inner comparison o.customer_id = c.customer_id is simply not true for the NULL row, so that row does not count as a match.
The LEFT JOIN form is also safe here. A NULL in orders.customer_id can never satisfy the ON condition, so that order row never joins to any customer.
| Form | Behavior when the subquery column has a NULL |
|---|---|
| `NOT EXISTS` | Correct, the NULL row never matches |
| `LEFT JOIN ... IS NULL` | Correct, the NULL row never joins |
| `NOT IN` | Returns no rows |
For absence checks, prefer NOT EXISTS or the LEFT JOIN form over NOT IN.
When the rewrite is not a drop-in replacement
Some join rewrites change results beyond duplicates. Check these before you convert a query.
- Duplicates on the right side. The
LEFT JOINanti-join form is safe from duplicates, as shown above. The inner-join semi-join form is not. If you cannot useDISTINCT, for example because you select columns that are not comparable or the result is large, stay withEXISTS. - Aggregates over a joined result. If you join and then
SUMa column from the left table, each left row is counted once per match. A customer'scredit_limitsummed across a join to orders is multiplied by the number of orders. A semi-join does not have this problem, because it never repeats left rows. - Correlated scalar subqueries. A subquery that returns one value per outer row, such as the latest order date, can be rewritten as a
LEFT JOINto a grouped derived table. The two forms agree only if the grouped table has one row per key. - Non-equality correlation.
EXISTSaccepts any condition inside the subquery, such aso.total > c.credit_limit. A join can express this too, but the duplicate-row andNULLanalysis has to be repeated for the new condition.
Here is the scalar subquery and its join form for item 3:
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;
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;Both return one row per customer, and both give NULL for customers with no orders. The scalar form is shorter. The join form is easier to extend when you need several aggregates from the same table, because one derived table can supply MAX, COUNT, and SUM together.
What the database actually does
SQL describes the result you want, and the optimizer chooses how to compute it. Most modern optimizers recognize EXISTS and NOT EXISTS and turn them into semi-join and anti-join operators internally. PostgreSQL shows these as Hash Semi Join and Hash Anti Join in EXPLAIN output. Other systems use different names, such as a semi-join or "left anti semi join" operator.
This has a practical consequence. The EXISTS form, the IN form, and in many cases the LEFT JOIN ... IS NULL form can end up with the same plan. Writing the join by hand for speed is often unnecessary. Choose the form that states the question most clearly, then read the plan if the query is slow.
Two exceptions are worth knowing:
- The optimizer does not always see through a
LEFT JOIN ... IS NULLfilter. Some systems plan it as a full outer-style join followed by a filter, which can be slower than theNOT EXISTSform. Others detect the pattern and use an anti-join. - An
INNER JOINwithDISTINCTis not rewritten into a semi-join in every system, because the optimizer would have to prove that dropping the duplicates is safe.
Whichever form you use, an index on the correlation column lets each lookup find matching orders directly instead of scanning the table:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);The next chapter covers indexing and plans in more detail. For now, the main point is that the choice between EXISTS and a join is mostly about correctness and readability, not about speed.
Decision guide
- Need only to know whether a match exists, and want each left row once: use
EXISTS. - Need columns from the matching rows: use
JOIN, and accept one row per match. - Need rows with no match: use
NOT EXISTS, orLEFT JOIN ... IS NULLwith the filters inON. AvoidNOT INunless the subquery column is declaredNOT NULL. - Need several aggregates per left row: join to a grouped derived table.
- Unsure: write both and compare the results with
EXCEPTor a row count, then compare the plans.
Exercise
A teammate rewrites "customers with no orders in 2026" as a LEFT JOIN to orders, with the condition o.orderdate >= DATE '2026-01-01' placed in the WHERE clause, followed by AND o.orderid IS NULL. The query returns no rows even though many customers have no 2026 orders. Explain why, and show the corrected query.
Show answer
For a customer with no matching order, the LEFT JOIN fills o.orderdate with NULL. The comparison NULL >= DATE '2026-01-01' is UNKNOWN, so the WHERE clause removes that row. The conditions o.orderdate >= ... and o.orderid IS NULL can never be true together, so nothing survives. Move the date condition into the ON clause: SELECT c.customerid, c.name FROM customers c LEFT JOIN orders o ON o.customerid = c.customerid AND o.orderdate >= DATE '2026-01-01' AND o.orderdate < DATE '2027-01-01' WHERE o.order_id IS NULL;
Exercise
Why does SELECT c.customerid, c.name FROM customers c JOIN orders o ON o.customerid = c.customer_id return more rows than the equivalent EXISTS query, and what are two ways to fix it?
Show answer
The join returns one row per matching order, so a customer with several orders is repeated. One fix is to add DISTINCT to the select list. The other is to rewrite the query with WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customerid = c.customerid), which never repeats a customer.