Sub topic 12
Performance considerations
This chapter assumes you can write UNION, INTERSECT, and EXCEPT queries, know how DISTINCT works, and have read an execution plan at least once. It covers what set operators cost, when to pick a cheaper form, and how to check your choice in your own database.
Where the cost comes from
A set operator runs two or more queries and then combines their results. Each branch is planned and run like a normal query. The combining step adds work that depends on the operator.
| Operator | Combining work | Typical cost |
|---|---|---|
| `UNION ALL` | Append the rows of one branch to the other | Almost none |
| `UNION` | Append, then remove duplicates | Sort or hash on every output column |
| `INTERSECT` | Find rows present in both inputs, remove duplicates | Sort-merge or hash on every column |
| `EXCEPT` | Find rows in the first input and not in the second, remove duplicates | Sort-merge or hash on every column |
The important difference is between UNION ALL and everything else. UNION ALL streams rows through. The other three must compare whole rows, so they need to see rows from both inputs before they can be sure a row is a duplicate or a match.
Duplicate removal is a sort or a hash
To remove duplicates, a database usually does one of two things.
- Sort and scan. It sorts all rows by every column, then drops adjacent equal rows. Sorting costs roughly n log n comparisons, and it needs memory or temporary disk space.
- Hash aggregate. It builds a hash table keyed on the whole row and keeps one row per key. This is often faster than sorting, but the table must fit in memory or spill to disk.
Both approaches scale with the number of rows and with the width of the rows. A UNION on ten wide text columns is much more expensive than a UNION on one integer column, because the database compares and hashes every column.
The plan below uses a UNION and shows the extra step. The exact output depends on your database and version.
EXPLAIN
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers;In PostgreSQL the plan typically contains an Append node under a HashAggregate or a Unique over a Sort. Replace UNION with UNION ALL and the aggregate or sort node disappears, leaving only the Append.
Prefer UNION ALL when duplicates cannot occur or do not matter
The most common and most valuable optimization is to write UNION ALL instead of UNION. It is safe in two situations:
- The branches cannot overlap, because they filter on disjoint conditions or come from different sources.
- Duplicates are acceptable, for example when you are going to aggregate the result anyway.
SELECT order_id, total FROM orders_2025
UNION ALL
SELECT order_id, total FROM orders_2026;If the two tables hold different years, no row can appear in both, so UNION would pay for a duplicate check that finds nothing. Be careful with the first situation: a single table can still contain duplicate rows internally, and UNION would remove those as well. If you rely on that cleanup, UNION ALL changes the result, not just the speed.
If you need distinct rows but the branches overlap, there is a middle path. Deduplicate once on the key columns instead of on wide rows.
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers;Selecting only the columns you need keeps the sort or hash key small. Adding extra columns "just in case" makes the operator slower and can also change which rows count as duplicates.
Push filters into each branch
The optimizer can often push a WHERE condition on the outer query into each branch, but it does not always do so, especially across INTERSECT and EXCEPT or when the branches are views. Write the filter inside each branch when you can.
-- Filter applied after combining: may process every row first
SELECT email
FROM (
SELECT email, country FROM customers
UNION ALL
SELECT email, country FROM newsletter_subscribers
) AS combined
WHERE country = 'DE';
-- Filter applied in each branch: each query can use an index on country
SELECT email FROM customers WHERE country = 'DE'
UNION ALL
SELECT email FROM newsletter_subscribers WHERE country = 'DE';Filtering early shrinks the inputs to the combining step, and it lets each branch use its own indexes. For UNION the two forms return the same rows. For INTERSECT and EXCEPT the same holds when the filter is on columns that are part of the compared row, but check it with a test rather than assuming.
Indexes help branches, not the combine step
Indexes speed up the individual SELECT statements. They rarely help the set operation itself, with some exceptions:
- If both branches can read rows already sorted by the compared columns, for example through an index scan, the database may use a merge approach and skip the explicit sort.
- If a branch reads only indexed columns, an index-only scan avoids touching the table.
Do not expect an index on email to make UNION itself fast when the branches are full-table scans that still return millions of rows. In that case the cost is dominated by reading, then sorting or hashing.
Large inputs and memory
Hash and sort steps use a memory budget. When the data exceeds it, the database writes temporary data to disk, and the query slows down sharply. Signs of this in a plan include Sort Method: external merge in PostgreSQL, or "spill" and "tempdb" warnings in other systems.
Ways to reduce the pressure:
- Select fewer and narrower columns.
- Filter each branch before combining.
- Use
UNION ALLwhere duplicates are harmless. - As a last resort, raise the per-query memory setting for that session, knowing that it multiplies across concurrent queries.
INTERSECT and EXCEPT versus joins and EXISTS
INTERSECT and EXCEPT are concise, but a join or EXISTS form can sometimes be faster or give the optimizer more room. The chapter on join and EXISTS alternatives covers the equivalence rules. Here the focus is on cost.
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email = s.email
);This query approximates the EXCEPT example. It can use an index on unsubscribed.email for each subscriber and stop at the first match, which is an anti-join. With a good index and a small s, that is often cheaper than hashing both whole tables. When both tables are large and you need most rows, a hash anti-join and EXCEPT often perform about the same, since many optimizers plan both forms alike.
Remember the semantic difference. EXCEPT treats two NULLs as equal, so it removes a NULL email from the first result if the second result also holds a NULL. The NOT EXISTS form compares with =, which never matches NULL, so a NULL email survives. Do not switch forms for speed without deciding which NULL behavior you want.
A quick guide:
| Situation | Reasonable choice |
|---|---|
| Small inputs, readability matters | `INTERSECT` or `EXCEPT` |
| One side is small and the other is indexed on the key | `EXISTS` or `NOT EXISTS` |
| You need columns from the other table | Join |
| Compared rows have many columns, with NULLs that should match | `INTERSECT` or `EXCEPT` |
Many branches and repeated scans
A UNION ALL of several branches that read the same table scans that table once per branch.
SELECT id, 'high' AS band FROM orders WHERE total >= 1000
UNION ALL
SELECT id, 'low' AS band FROM orders WHERE total < 1000;This reads orders twice. A single scan with a CASE expression does the same work in one pass:
SELECT id,
CASE WHEN total >= 1000 THEN 'high' ELSE 'low' END AS band
FROM orders;The two are equivalent only when every row falls into exactly one branch. Here a NULL total appears in neither branch of the first query but gets 'low' in the second, because the CASE falls through to ELSE. Add WHEN total IS NOT NULL logic if that matters. Rewrite repeated scans like this when the table is large, and leave them when the branches read different tables or use very different filters that each hit an index.
Measure before you rewrite
Plans vary with data size, statistics, and database version. Use the plan, not intuition.
- Run
EXPLAIN(orEXPLAIN ANALYZEin PostgreSQL, which runs the query) on the current form. - Note the row counts at each step, the sort or hash node, and any spill to disk.
- Write the alternative form and compare plans and timings on realistic data.
- Confirm that both forms return the same rows, including NULL and duplicate cases.
Summary of decisions
- Default to
UNION ALLwhen you know duplicates cannot occur or do not matter. UseUNIONonly when you need deduplication. - Keep the compared column list short.
- Filter inside each branch.
- Use
EXISTSor a join when an index lets the database stop early, and keepINTERSECTorEXCEPTwhen NULL-equal behavior is what you want. - Merge repeated scans of one table into one scan when each row belongs to one group.
- Check the plan before and after.
Exercise
The tables sales_east and sales_west each have columns sale_id and amount, and a sale is stored in exactly one of them. A report runs SELECT sale_id, amount FROM sales_east UNION SELECT sale_id, amount FROM sales_west and is slow. What change would you try first, and what must be true for it to return the same rows?
Show answer
Change UNION to UNION ALL, which skips the sort or hash step that removes duplicates. The result is identical only if no row appears in both tables and neither table holds fully duplicate rows internally. Since each sale lives in exactly one table, the first condition holds, but check the second, for example by confirming sale_id is a primary key in each table.
Exercise
A query uses SELECT email FROM newsletter_subscribers EXCEPT SELECT email FROM unsubscribed. You rewrite it with NOT EXISTS for speed, and the result gains one extra row. What is the likely cause?
Show answer
A row whose email is NULL. EXCEPT treats NULLs as equal, so a NULL in newsletter_subscribers is removed when unsubscribed also contains a NULL. In the NOT EXISTS version, u.email = s.email is never true for NULL, so the subquery finds no match and the NULL row is kept. Add AND s.email IS NOT NULL or use IS NOT DISTINCT FROM where supported to match the original behavior.