SQL Set Operations: UNION, UNION ALL, INTERSECT and EXCEPT
How to combine the results of several queries: UNION and UNION ALL to stack rows, INTERSECT for rows in both, EXCEPT (MINUS in Oracle) for rows in one but not the other, the ALL variants, the column and type rules, ORDER BY and LIMIT with set operations, precedence, NULL handling and performance.
kvi5hnuCode Sprout team member9 min readOn this page
Joins combine tables side by side: each result row has columns from several tables. Set operations combine query results one on top of another: the result has the columns of one query and rows from several. They answer questions such as "all the cities where we have customers or suppliers", "products bought by both of these customers" and "products that were never ordered".
| Operator | Result |
|---|---|
A UNION B | the distinct rows that are in A or B (or both) |
A UNION ALL B | all rows of A followed by all rows of B, duplicates kept |
A INTERSECT B | the distinct rows that are in both A and B |
A EXCEPT B | the distinct rows of A that aren't in B (MINUS in Oracle) |

The examples use the shop database from article 12, plus a small suppliers table.
UNION and UNION ALL
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
CREATE TABLE suppliers (supplier_id INTEGER PRIMARY KEY, name VARCHAR(40), city VARCHAR(30));
INSERT INTO suppliers VALUES (1, 'Alpina Outdoor', 'Leeds'), (2, 'Lumen Ltd', 'Bristol'), (3, 'Woolly Mills', NULL);
-- UNION: the distinct cities we have contacts in
SELECT city FROM customers
UNION
SELECT city FROM suppliers
ORDER BY city;
-- UNION ALL keeps every row, duplicates included
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers
ORDER BY city;
-- A combined contact list, with a label saying where each row came from
SELECT name, city, 'customer' AS contact_type FROM customers WHERE city IN ('Leeds', 'York')
UNION ALL
SELECT name, city, 'supplier' FROM suppliers
ORDER BY contact_type, name;
city
---------
Bristol
Leeds
Pune
York
(null)
(5 rows)
city
---------
Bristol
Leeds
Leeds
Leeds
Pune
Pune
York
(null)
(null)
(9 rows)
name | city | contact_type
----------------+---------+--------------
Ben Okafor | Leeds | customer
Dana Cruz | York | customer
Eli Novak | Leeds | customer
Alpina Outdoor | Leeds | supplier
Lumen Ltd | Bristol | supplier
Woolly Mills | (null) | supplier
(6 rows)
UNIONreturned five distinct cities. Leeds appears in both tables, but only once in the result. Removing duplicates treats NULLs as equal (asDISTINCTdoes, article 8), so the NULL city of Farah and the NULL city of Woolly Mills became one row.UNION ALLreturned all nine rows: six customers and three suppliers.- The labelled list adds a constant column,
'customer'or'supplier', to each branch. This is the standard way to record where each row came from. It also means rows from different branches can never be duplicates of each other.
Prefer UNION ALL
UNION must find and remove duplicates, which means sorting or hashing the whole combined result. UNION ALL just appends the rows. So:
- Use
UNION ALLwhen duplicates can't occur, for example when the branches have different labels or filter on non-overlapping conditions, or when you want them, as when combining this year's and last year's sales before adding them up. - Use
UNIONonly when you need duplicates removed.
Using UNION by habit has two costs: it's slower on large results, and it can silently remove rows that were legitimately identical, such as two genuine orders for the same amount on the same day. If you then add the amounts up, the total is wrong.
INTERSECT and EXCEPT
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Products bought by customer 1 AND by customer 2
SELECT oi.product_id FROM order_items oi JOIN orders o ON o.order_id = oi.order_id WHERE o.customer_id = 1
INTERSECT
SELECT oi.product_id FROM order_items oi JOIN orders o ON o.order_id = oi.order_id WHERE o.customer_id = 2;
-- Products that have never been ordered
SELECT product_id FROM products
EXCEPT
SELECT product_id FROM order_items
ORDER BY product_id;
-- EXCEPT ALL subtracts occurrences: products that were ordered more than once
SELECT product_id FROM order_items
EXCEPT ALL
SELECT product_id FROM products
ORDER BY product_id;
product_id
------------
3
(1 row)
product_id
------------
4
(1 row)
product_id
------------
3
7
7
(3 rows)
INTERSECTreturned the products bought by both customer 1 and customer 2. Only the Glow head torch (product 3) was bought by both Asha and Ben.EXCEPTreturned the products that appear inproductsbut never inorder_items: only the lantern (4). This is a neat way to write an anti-join (article 16) when you only need the key columns.EXCEPT ALLsubtracts occurrences instead of distinct rows. Product 3 appears twice inorder_itemsand once inproducts, so one occurrence is left. Product 7 appears three times, so two are left. Products ordered only once disappear.INTERSECT ALLsimilarly keeps the smaller of the two counts for each row.
Product support varies:
| Operator | PostgreSQL | Oracle | SQL Server | MySQL | SQLite |
|---|---|---|---|---|---|
UNION, UNION ALL | yes | yes | yes | yes | yes |
INTERSECT, EXCEPT | yes | yes (EXCEPT from 21c, MINUS in all versions) | yes | 8.0.31+ | yes |
INTERSECT ALL, EXCEPT ALL | yes | 21c+ (MINUS ALL too) | no | 8.0.31+ | no |
Where INTERSECT or EXCEPT aren't available, write them with EXISTS and NOT EXISTS (article 16). Those also let you compare only some columns, while the set operators always compare entire rows.
The rules
Same number of columns, compatible types
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- The branches must have the same number of columns...
SELECT name, city FROM customers
UNION
SELECT name FROM products;
-- ...and compatible types, column by column
SELECT customer_id, name FROM customers
UNION
SELECT name, product_id FROM products;
-- Column names come from the first branch; ORDER BY sorts the whole result
SELECT name AS label, 'product' AS kind FROM products WHERE category = 'tents'
UNION ALL
SELECT name, 'customer' FROM customers WHERE city = 'Pune'
ORDER BY label;
-- To limit one branch, put it in parentheses
(SELECT name FROM products ORDER BY price DESC LIMIT 1)
UNION ALL
(SELECT name FROM products ORDER BY price LIMIT 1);
psql:/workspace/solution.sql:65: ERROR: each UNION query must have the same number of columns
LINE 3: SELECT name FROM products;
^
psql:/workspace/solution.sql:70: ERROR: UNION types integer and character varying cannot be matched
LINE 3: SELECT name, product_id FROM products;
^
label | kind
---------------+----------
Asha Rao | customer
Chen Wei | customer
Ridge 2 tent | product
Summit 4 tent | product
(4 rows)
name
---------------
Summit 4 tent
Merino socks
(2 rows)
- Every branch must return the same number of columns. The first query fails because one branch has two columns and the other has one.
- Columns are matched by position, not by name, and each position must have compatible types in every branch. The second query puts a number above a name, so it fails. If the types had been compatible, say two text columns in the wrong order, the query would have run and silently mixed up the columns. Always check that each position means the same thing in every branch.
- The result's column names come from the first branch. The third query's columns are
labelandkind, even though the second branch doesn't name them.
ORDER BY and LIMIT apply to the whole result
An ORDER BY after the last branch sorts the combined result, and it can only refer to the result's columns, by the first branch's names or by position. You can't sort an individual branch that way, and ORDER BY inside a branch is either an error or ignored, because set operations don't preserve order.
To limit one branch, for example to get the most expensive and the cheapest product, put that branch in parentheses with its own ORDER BY and LIMIT, as in the last query. In SQL Server and SQLite, wrap each branch in a derived table: SELECT * FROM (SELECT TOP (1) ... ORDER BY ...) AS t.
Precedence
INTERSECT binds more tightly than UNION and EXCEPT, so A UNION B INTERSECT C means A UNION (B INTERSECT C). UNION and EXCEPT have equal precedence and are evaluated left to right, so A EXCEPT B UNION C means (A EXCEPT B) UNION C. Use parentheses whenever you mix operators. Oracle is an exception: all its set operators have equal precedence and are evaluated left to right, so the same query can mean different things in Oracle and in other products. Parentheses make it mean the same everywhere.
Duplicates and NULLs
Set operators compare rows the way DISTINCT does: two rows are duplicates if every column is equal, with NULLs counted as equal. That's different from = in a WHERE clause. (1, NULL) INTERSECT (1, NULL) returns the row, while a join on a.x = b.x would never match two NULLs. This makes EXCEPT useful for comparing tables that contain NULLs (article 17).
Set operations and data types
When the types in a position differ but are compatible, the result uses a common type. Combining an INTEGER column with a DECIMAL(8, 2) gives a decimal, and combining VARCHAR(10) with VARCHAR(40) gives a type long enough for both. Untyped literals, such as NULL or 'x', take the type of the other branches. If a branch only has a NULL in some position, PostgreSQL may need a hint, as in CAST(NULL AS DATE), when no other branch fixes the type.
What's current
- MySQL 8.0.31 (2022) added
INTERSECTandEXCEPT, including theALLforms, so every major product now supports them except for theALLforms in SQL Server and SQLite. - Oracle 21c added the standard
EXCEPTkeyword and theALLvariants (EXCEPT ALL,INTERSECT ALL,MINUS ALL). Oracle still gives all set operators equal precedence. - Oracle 26ai keeps
MINUSas a synonym forEXCEPT, so older code continues to work.
Common questions
What's the difference between UNION and UNION ALL?
UNION removes duplicate rows from the combined result. UNION ALL keeps every row and is faster. Use UNION ALL unless you need duplicates removed.
Do the column names have to match? No. Columns are matched by position, and the result takes its names from the first branch. Only the number of columns and their types must agree.
Can I use ORDER BY in each branch?
Not directly. One ORDER BY at the end sorts the whole result. To sort and limit a branch, put it in parentheses (PostgreSQL, MySQL) or wrap it in a derived table (SQL Server, SQLite): SELECT * FROM (SELECT ... ORDER BY ... LIMIT 1) AS t.
Is EXCEPT the same as MINUS?
Yes. MINUS is Oracle's name, and Oracle 21c and later accept EXCEPT too.
Is a set operation better than a join or EXISTS?
For whole-row comparisons, set operators are short and treat NULLs as equal, which is often what you want. For "rows of A related to B" questions where you need A's other columns, EXISTS or a join is more flexible. Modern optimizers often produce similar plans.
How do I combine more than two queries?
Chain them: A UNION ALL B UNION ALL C. Use parentheses when you mix different operators.
Summary
- Set operations stack the results of several queries.
UNIONgives distinct rows from either,UNION ALLall rows,INTERSECTrows in both, andEXCEPT(Oracle:MINUS) rows of the first that aren't in the second. - Every branch must have the same number of columns, with compatible types position by position. Names come from the first branch.
- Prefer
UNION ALL.UNIONcosts a sort or hash, and can remove legitimate duplicate rows. - A constant label column in each branch records where each row came from.
ORDER BYat the end sorts the whole result. Parenthesize a branch to sort or limit it on its own.INTERSECTbinds more tightly thanUNIONandEXCEPT(except in Oracle). Use parentheses when mixing them.- Set operators treat NULLs as equal when comparing rows. The
ALLforms count occurrences.
Practice questions
Write a query that returns every city where the shop has a customer or a supplier, without duplicates and without the NULL city.
Answer
SELECT city FROM customers WHERE city IS NOT NULL
UNION
SELECT city FROM suppliers WHERE city IS NOT NULL
ORDER BY city;
The result is Bristol, Leeds, Pune and York. Each branch filters its own rows. A WHERE clause after the last branch would only apply to the last branch, not to the whole result.
A report combines two monthly sales tables with SELECT customer_id, amount FROM sales_jan UNION SELECT customer_id, amount FROM sales_feb, then sums amount per customer. Some customers' totals are too low. Why?
Answer
UNION removes duplicate rows. A customer who spent the same amount in January and February, say 40.00 each month, produces two identical rows, (customer_id, 40.00), and UNION keeps only one, so the total loses 40.00. Use UNION ALL, which keeps every row. Adding a label column, such as 'jan' AS month, would also make the rows distinct.
Write a query that returns the IDs of customers who have placed at least one order but have never had an order shipped.
Answer
SELECT customer_id FROM orders WHERE customer_id IS NOT NULL
EXCEPT
SELECT customer_id FROM orders WHERE status = 'shipped'
ORDER BY customer_id;
The first branch lists customers with orders (1, 2, 3 and 4). The second lists those with a shipped order (1 and 2). The result is customers 3 and 4: Chen, whose order is pending, and Dana, whose order was cancelled.
What does this query return, and why?
SELECT 1 AS n UNION SELECT 2 INTERSECT SELECT 2 UNION SELECT 3 EXCEPT SELECT 1;
Answer
It returns 2 and 3. INTERSECT binds most tightly, so the query means ((1 UNION (2 INTERSECT 2)) UNION 3) EXCEPT 1. 2 INTERSECT 2 is 2, so the unions give {1, 2, 3}, and EXCEPT 1 removes 1. Without an ORDER BY, the order of the two rows isn't guaranteed.
Previous: Self Joins, Cross Joins and Non-Equi Joins in SQL
Next: Finding Matches and Missing Rows: EXISTS, NOT EXISTS, IN and NOT IN

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.