Sub topic 1
Combining result sets: the idea behind set operators
A set operator takes the result sets of two queries and produces one new result set. SQL has three of them: UNION, INTERSECT, and EXCEPT. This chapter gives you the working model they all share. Later chapters cover each operator, NULL handling, ordering, precedence, and dialect differences in detail.
Prerequisites
This chapter assumes you can already do the following:
- Write a basic
SELECTwith aWHEREclause. - Describe a table in terms of rows and columns.
- Use
DISTINCTandORDER BY. - Explain what
NULLmeans: an unknown or missing value, not zero and not an empty string.
You don't need to know joins or subqueries yet. They appear briefly at the end for comparison.
The core idea: a query result is a table
A SELECT statement returns rows with named, typed columns. That output has the same shape as a table, so you can treat it as an input to something else. You already do this with subqueries and views.
A set operator takes two such inputs and combines them by rows. A join works differently. It places columns from two tables side by side, matched by a condition. A set operator stacks or compares whole rows. The columns stay the same, and the rows are combined, intersected, or subtracted.
The name comes from set theory, where you combine collections with union, intersection, and difference. SQL borrows the vocabulary but is not purely set-based. Tables can hold duplicate rows, so each operator has to decide what to do with them. That decision is the main thing that separates UNION from UNION ALL.
| Operator | Result contains | Mathematical analogy |
|---|---|---|
| `UNION` | Rows found in either query, duplicates removed | A ∪ B |
| `UNION ALL` | All rows from both queries, duplicates kept | Not a pure set operation |
| `INTERSECT` | Rows found in both queries | A ∩ B |
| `EXCEPT` | Rows from the first query that are absent from the second | A − B |
A small data set to work with
The examples in this tutorial use three one-column tables. Each holds email addresses. The script below runs as written in PostgreSQL and SQLite.
CREATE TABLE customers (email TEXT);
CREATE TABLE newsletter_subscribers (email TEXT);
CREATE TABLE unsubscribed (email TEXT);
INSERT INTO customers VALUES
('[email protected]'),
('[email protected]'),
('[email protected]');
INSERT INTO newsletter_subscribers VALUES
('[email protected]'),
('[email protected]'),
('[email protected]'),
('[email protected]');
INSERT INTO unsubscribed VALUES
('[email protected]');The tables are deliberately unconstrained. newsletter_subscribers contains [email protected] twice, which lets you see how each operator treats duplicates.
The shape of every set operation
Every set operation has the same structure:
SELECT ... -- left query
<operator>
SELECT ... -- right queryThe database runs both queries and then combines their results according to the operator. The two queries are independent. Each has its own FROM, WHERE, GROUP BY, and joins. The set operator only sees the finished rows.
Three consequences follow from this model.
- Column names come from the first query. The final result uses the left query's column names or aliases. Aliases in the right query are ignored. This is why a later chapter says that an
ORDER BYon a combined result refers to the first query's columns. - Rows are compared by value, across all columns. Two rows count as the same only if every column matches. A row with the same email and a different
sourcelabel is a different row. - Order is not guaranteed. The operators don't promise any row order. If order matters, add
ORDER BYat the end.
The three operators in action
UNION
UNION returns every distinct row found in either input.
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers;The result is four rows: ana, ben, cho, and dev. ben and cho appear in both tables but are returned once. The repeated dev row inside newsletter_subscribers is also collapsed. UNION removes duplicates across the two inputs and within each one.
UNION ALL
UNION ALL skips duplicate removal.
SELECT email, 'customer' AS source FROM customers
UNION ALL
SELECT email, 'subscriber' AS source FROM newsletter_subscribers;The result has seven rows: three from customers and four from newsletter_subscribers, including both dev rows. The literal 'customer' and 'subscriber' values show where each row came from. Adding a label column like this is a common way to keep track of provenance.
INTERSECT
INTERSECT returns the distinct rows that appear in both inputs.
SELECT email FROM customers
INTERSECT
SELECT email FROM newsletter_subscribers;The result is ben and cho. These are customers who also subscribe to the newsletter.
EXCEPT
EXCEPT returns the distinct rows from the first input that don't appear in the second.
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed;The result is ben and dev. Here cho is removed because that address is in unsubscribed.
Unlike the other two, EXCEPT is not symmetric. Swapping the inputs gives a different answer:
SELECT email FROM unsubscribed
EXCEPT
SELECT email FROM newsletter_subscribers;This returns no rows, because the only unsubscribed address, cho, is also in the subscriber list. UNION and INTERSECT give the same rows whichever input comes first. EXCEPT does not.
Duplicates: the main design decision
The simplest rule of thumb has two parts:
UNION,INTERSECT, andEXCEPTreturn distinct rows by default.UNION ALLis the form that keeps duplicates.
Removing duplicates costs work. The database usually has to sort or hash all the rows to find matches. UNION ALL just appends one result to the other, so it is typically cheaper. If you know the inputs can't overlap, or you want the duplicates, UNION ALL is the right choice. If you need unique rows, use UNION. The chapters on UNION, UNION ALL, and performance go into this in depth.
Common errors
Most set operator errors come from a few causes.
A different number of columns. Both queries must return the same number of columns. This fails in every mainstream database:
SELECT email FROM customers
UNION
SELECT email, 'subscriber' FROM newsletter_subscribers;The error message varies by system. PostgreSQL says that each UNION query must have the same number of columns. Fix it by matching the column lists. The next chapter covers how to do this, including type compatibility.
Matching by position, not by name. The database pairs the first column of the left query with the first column of the right, then the second with the second, and so on. Column names are never used for matching. If you list the same columns in a different order, the query may still run if the types happen to be compatible, but the result will be wrong. This is the most dangerous mistake because it often produces no error.
Forgetting that duplicates disappear. If you use UNION to merge two sets of orders and then count the rows, identical rows collapse, and the count comes out too low. Use UNION ALL when you are counting or summing.
Expecting a sorted result. The output of UNION often looks sorted because some engines sort rows to remove duplicates. That is an implementation detail. Don't depend on it.
When a set operator fits, and when it doesn't
A set operator is a good fit when you want to combine or compare whole result sets that come from different tables or different queries. Typical cases:
- Merging similar data from separate tables, such as
orders_2024andorders_2025. - Building a single list from several sources, such as all contact emails.
- Finding rows present in one source but missing from another, such as customers who never subscribed.
It is a weaker fit when you need columns from both sides together. To list each customer along with their subscription date, you need a join. Many INTERSECT and EXCEPT queries can also be rewritten with joins or EXISTS. Both forms are covered in a later chapter, along with the NULL differences between them. As a preview, this query is close to the EXCEPT example above:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email = s.email
);It returns the same rows for this data. It can differ when emails are NULL, because = never matches NULL, while EXCEPT treats two NULLs as equal.
Support across databases
UNION, UNION ALL, INTERSECT, and EXCEPT are part of standard SQL and work in PostgreSQL, SQLite, and SQL Server. Oracle spells EXCEPT as MINUS. Older versions of MySQL lack INTERSECT and EXCEPT, and the ALL variants of INTERSECT and EXCEPT are missing in several systems. Check your database's documentation before relying on any of these. A later chapter collects the differences in one place.
Summary of the working model
- A set operator combines two result sets row by row. A join combines columns instead.
- Both queries run independently, and the operator works on their finished results.
- Rows are matched by position and compared by full-row value.
- The result takes its column names from the first query.
UNION,INTERSECT, andEXCEPTremove duplicates.UNION ALLkeeps them.EXCEPTdepends on input order. The other operators don't.- No row order is guaranteed without
ORDER BY.
Exercise
Using the three tables from this chapter, how many rows does each query return, and why? (a) SELECT email FROM newslettersubscribers UNION SELECT email FROM newslettersubscribers; (b) SELECT email FROM newslettersubscribers UNION ALL SELECT email FROM newslettersubscribers;
Show answer
(a) 3 rows: ben, cho, and dev. UNION removes duplicates across both inputs and within each one, so the repeated dev row collapses. (b) 8 rows. UNION ALL appends the 4 rows of the second input to the 4 rows of the first and removes nothing, so dev appears four times.
Exercise
You want the customers who are not newsletter subscribers. Write the query with a set operator, and say what you get with the sample data. What happens if you swap the two inputs?
Show answer
SELECT email FROM customers EXCEPT SELECT email FROM newsletter_subscribers; returns only [email protected], because ben and cho are in both tables. Swapping the inputs gives the subscribers who are not customers, which is [email protected]. EXCEPT is not symmetric, so the order of the inputs changes the result.