Sub topic 12
Performance Considerations for SQL Set Operations
This chapter assumes you can write SELECT queries with WHERE, understand duplicate rows and NULL, and use basic ORDER BY. The main performance question is how much data the database must read, combine, sort, and compare.
Why set operations cost time
A set operation combines complete query results. The database may need to do these steps:
- Run the input queries.
- Move or combine their rows.
- Remove duplicates or find matching rows.
- Sort or hash the intermediate result.
- Return the final rows.
UNION ALL usually has the lowest overhead because it appends rows without removing duplicates.
SELECT email FROM customers
UNION ALL
SELECT email FROM newsletter_subscribers;UNION, INTERSECT, and EXCEPT normally need duplicate handling. A database may use a sort or a hash structure for this work. The exact plan depends on the database system, table sizes, indexes, and available memory.
Reduce rows before combining them
Filter each input query as early as possible. A filter applied inside an input query can reduce the number of rows that the set operation must process.
SELECT email
FROM customers
WHERE status = 'active'
UNION ALL
SELECT email
FROM newsletter_subscribers
WHERE confirmed_at IS NOT NULL;Selecting only the needed columns also reduces memory use and data transfer. Set operations compare the selected row values, so avoid including columns that do not affect the result.
Indexes can help the input queries find filtered rows quickly. An index is a data structure that helps a database locate rows without scanning the entire table. However, an index does not guarantee that the final UNION or EXCEPT will avoid sorting or hashing.
Inspect the execution plan
An execution plan shows how the database expects to run a query. Many systems support EXPLAIN; some also support a form such as EXPLAIN ANALYZE, which executes the query and reports actual timing and row counts.
EXPLAIN
SELECT email
FROM customers
WHERE status = 'active'
UNION
SELECT email
FROM newsletter_subscribers
WHERE confirmed_at IS NOT NULL;Look for these signals:
| Plan signal | What it may indicate |
|---|---|
| Sequential or full table scan | Many rows are being read, or an index is not useful |
| Sort or hash for duplicate removal | `UNION`, `INTERSECT`, or `EXCEPT` is doing set-based comparison |
| Large intermediate row count | Filters may need to move into the input queries |
| Repeated scans | The same table or expensive expression may be evaluated more than once |
A plan's cost is an estimate, not a guarantee. Test with representative data and production-like filters.
Compare set operations with joins and EXISTS
A set operation often clearly expresses a relationship between result sets. A join or EXISTS query can sometimes give the optimizer more options, especially when one query only checks whether a matching row exists.
For example, this query finds active customers who are also subscribers:
SELECT DISTINCT c.email
FROM customers AS c
WHERE c.status = 'active'
AND EXISTS (
SELECT 1
FROM newsletter_subscribers AS s
WHERE s.email = c.email
);An index on newsletter_subscribers(email) may make the existence check efficient. The best choice depends on data distribution and indexes, so compare plans rather than relying on a general rule.
A set operation can still be preferable when it is easier to read, when both independent result sets are needed, or when the database optimizes it well.
Practical decision rule
- Choose
UNION ALLwhen every row should remain. - Choose
UNIONwhen duplicate rows must be removed. - Filter and project columns before the set operation.
- Add indexes for selective filters and matching predicates.
- Use
EXPLAINto verify the actual plan. - Compare
EXISTS, joins, and set operations when performance matters.
Exercise
You need every email from two tables, including repeated emails. Which operator should you start with, and why?
Show answer
Start with UNION ALL. It appends both results without the duplicate-removal work required by UNION.