Skip to content
Silver 6 min read · Set operations 3 practice problems ↓

UNION, INTERSECT and EXCEPT

Joins put tables side by side. Set operations stack them on top of each other: all rows from both, the rows they share, or the rows only one of them has. They are the quickest way to compare two copies of the same data.

Foundations · SQL for data engineers · Silver · Structure, sets and dates, lesson 2 of 3

Read first: Inner and outer joins (skip if you know it)

In plain words first

Think of each query result as a list of names. Set operations combine two lists:

UNION ALL

Both lists, one after the other. Nothing removed.

UNION

Both lists, with duplicates removed.

INTERSECT

Only the names that are on both lists.

EXCEPT

The names on the first list that are not on the second.

The examples compare customers who ordered early in the week (1 to 2 March) with those who ordered late (5 to 6 March).

UNION ALL and UNION

Spark SQL · UNION ALL keeps every row

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id FROM orders WHERE order_date <= '2026-03-02'
UNION ALL
SELECT customer_id FROM orders WHERE order_date >= '2026-03-05'

Eight rows: four early orders and four late ones, with customer 1 three times. UNION removes the duplicates:

Spark SQL · UNION removes duplicates

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id FROM orders WHERE order_date <= '2026-03-02'
UNION
SELECT customer_id FROM orders WHERE order_date >= '2026-03-05'
ORDER BY customer_id
Default to UNION ALL: Removing duplicates means comparing every row with every other, which on a cluster is a full shuffleshuffle: Moving rows across the network so that rows with the same key end up in the same task. Shown as Exchange in a plan. Learn more →. When you know the parts cannot overlap (different days, different sources with a source column), UNION ALL gives the same answer for much less work. Use UNION only when you really want duplicates gone.

An ORDER BY at the end sorts the combined result, not the last query. To label where each row came from, add a constant column:

Spark SQL · Row counts from two tables in one result

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06

Input: payments

order_idamount
201420
202650
203300
204540
205280
206450
207390
209650
211120
SELECT 'orders' AS source, count(*) AS row_count FROM orders
UNION ALL
SELECT 'payments', count(*) FROM payments

INTERSECT and EXCEPT

Spark SQL · Customers who ordered early and late

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id FROM orders WHERE order_date <= '2026-03-02'
INTERSECT
SELECT customer_id FROM orders WHERE order_date >= '2026-03-05'
Spark SQL · Customers who ordered early but never again

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id FROM orders WHERE order_date <= '2026-03-02'
EXCEPT
SELECT customer_id FROM orders WHERE order_date >= '2026-03-04'

Meera (customer 3) ordered on the 2nd and not after. EXCEPT is one-directional: A EXCEPT B is not the same as B EXCEPT A. Spark also accepts MINUS as another name for EXCEPT.

INTERSECT and EXCEPT also remove duplicates. Their ALL versions keep count: if a row appears 3 times on the left and once on the right, EXCEPT ALL keeps it twice.

The rules: same columns, matched by position

Both queries must return the same number of columns, and the columns are matched by position, not by name. The result takes its column names from the first query. Swap two columns of the same type and nothing fails: the values are silently mixed up.

Spark SQL · Columns swapped: no error, wrong data
SELECT order_id, customer_id FROM orders WHERE order_id = 201
UNION ALL
SELECT customer_id, order_id FROM orders WHERE order_id = 202

Output

order_id | customer_id
201      | 1
2        | 202

The second row claims order 2 belongs to customer 202. Always list the columns in the same order in every part, and never use SELECT * on both sides of a set operation: a column added to one table later shifts everything.

NULLs count as equal here

In a join, NULLNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more → never matches NULL. In set operations, two NULLs are treated as the same value, so a row with a NULL can be found in both inputs:

Spark SQL · A row with NULL is in both sides
SELECT * FROM VALUES (1, NULL), (2, 'x') AS t(id, note)
INTERSECT
SELECT * FROM VALUES (1, NULL), (2, 'y') AS t(id, note)

That makes EXCEPT a NULL-safe way to compare two tables, where a join on every column would quietly miss rows with NULLs.

Reconciling two sources

The payments table is what the payment provider says it collected. Does it agree with orders? EXCEPT in both directions answers it:

Spark SQL · What does each side have that the other lacks?

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06

Input: payments

order_idamount
201420
202650
203300
204540
205280
206450
207390
209650
211120
SELECT 'missing in payments' AS problem, order_id, amount
FROM (SELECT order_id, amount FROM orders
      EXCEPT
      SELECT order_id, amount FROM payments)
UNION ALL
SELECT 'missing in orders', order_id, amount
FROM (SELECT order_id, amount FROM payments
      EXCEPT
      SELECT order_id, amount FROM orders)
ORDER BY order_id, problem

Three kinds of difference show up: 208 and 210 were never paid, 211 was paid but has no order, and 206 appears on both sides because the amounts differ (540 against 450). When the result is empty, the two tables hold exactly the same rows.

Common mistakes

  • UNION when UNION ALL would do — UNION removes duplicates with an expensive shuffle. If the parts cannot overlap, use UNION ALL.
  • Columns in a different order in each part — They are matched by position, so values land in the wrong column with no error. List columns in the same order everywhere.
  • SELECT * in a set operation — A new column in one table shifts or breaks the match. Name the columns.
  • Checking only one direction — A EXCEPT B finds what B lacks, not what A lacks. Reconcile in both directions.

Key takeaways

  • UNION ALL stacks rows; UNION also removes duplicates, at a cost.
  • INTERSECT keeps rows in both; EXCEPT keeps rows in the first and not the second.
  • Columns are matched by position, and names come from the first query.
  • Set operations treat NULLs as equal, unlike joins.
  • Reconcile two sources with EXCEPT in both directions.

Interview prep

THE QUESTION

"Two tables should hold the same data. How do you check, in SQL, that they do?"

Count rows on both sides first, then run EXCEPT in both directions, (A EXCEPT B) UNION ALL (B EXCEPT A), labelling each side. Empty means the same set of rows; EXCEPT treats NULLs as equal, so rows with NULLs compare correctly, which a join on every column would not. Two caveats: EXCEPT removes duplicates, so use EXCEPT ALL (or compare counts per key) if duplicate rows matter; and for very wide tables, comparing a hash of each row first is cheaper.

Avoid: "Join the two tables on every column and count the matches." Rows with a NULL in any column never match in a join, so they show up as differences that are not real, or are missed entirely.

Follow-ups · answer out loud, then open

Follow-up"UNION or UNION ALL: which is faster, and why?"
UNION ALL: it just appends. UNION must also remove duplicates, which means a shuffle and a comparison of whole rows, like a DISTINCT over the result. Use UNION only when duplicates are possible and unwanted.
Scenario"Daily files from two vendors have the same columns in a different order. You UNION ALL them and totals look wrong."
Set operations match columns by position, so the vendors' columns were mixed up with no error. Name the columns in the same order in each SELECT; in the DataFrame API, unionByName matches by name and can fill missing columns with NULL.
Trap"A EXCEPT B returns nothing. Are the tables identical?"
Not necessarily. Every row of A is in B, but B may have extra rows, and EXCEPT ignores how many times a row appears. Check B EXCEPT A as well, and compare counts (or use EXCEPT ALL) if duplicates matter.

Check yourself

4 questions

Query A returns 4 rows and query B 4 rows, 2 of them identical to rows of A. How many rows does UNION ALL return?

Show the answer

8. UNION ALL keeps every row.

How are the columns of the two queries matched?

Show the answer

By position. Position only; names come from the first query.

Does (1, NULL) INTERSECT (1, NULL) return a row?

Show the answer

Yes. Set operations treat two NULLs as equal.

A EXCEPT B is empty. What do you know?

Show the answer

Every row of A is also in B. B may still have rows A lacks: check B EXCEPT A too.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Structure, sets and dates · lesson 3 of 3 · 6 min read
Dates and date spines
Weeks, months and date arithmetic, half-open ranges, and a calendar that keeps days with no data.

Related lessons

Previous: CTEs and subqueries

Primary sources: Set operators