Skip to content
Visual explainer 1h 30m to learn 3 steps

UNION, INTERSECT, EXCEPT & DISTINCT

Combine and compare result sets.

By Invicly Tech, , in SQL & PostgreSQL. About 8 minutes to read.

Topic 7 of 30

In short

Set operations stack or compare the results of two queries with the same number of compatible columns. UNION combines, INTERSECT keeps common rows, EXCEPT keeps rows from the first not in the second.

Explained simply

Joins put tables side by side, adding columns. Set operations stack results on top of each other, adding rows. They take two finished query results and combine them into one list.

Think of two guest lists for a party, one from you and one from a friend. UNION is the combined list with each name once. INTERSECT is the people on both lists. EXCEPT is the people on your list who are not on your friend's.

The two lists must have the same shape: the same number of columns, in the same order, with types that fit together. The column names in the final result come from the first query.

DISTINCT is the single-query cousin of these tools. It removes duplicate rows from one result, so each unique combination of the selected columns appears just once.

Press Play on a diagram to walk through it one step at a time.

CompareCombining two result sets A and B
UNION / UNION ALL
  • Rows in A or B
  • UNION removes duplicates
  • UNION ALL keeps all, faster
INTERSECT
  • Rows in both A and B
  • Duplicates removed
  • Like an AND across queries
EXCEPT
  • Rows in A but not B
  • Order of queries matters
  • Great for finding gaps
FlowWhat UNION does behind the scenes
  1. 1
    Run query A

    e.g. 900 customer emails

  2. 2
    Run query B

    e.g. 400 subscriber emails

  3. 3
    Append

    1,300 rows: this is UNION ALL

  4. 4
    Sort or hash

    Find identical rows

  5. 5
    Drop duplicates

    1,100 unique emails: this is UNION

In depth

What "duplicate" means here

UNION, INTERSECT, EXCEPT and DISTINCT compare whole rows, using every selected column. Two rows are duplicates only if every column matches. ('Ann', 'Berlin') and ('Ann', 'Paris') are different rows.

For this comparison, NULLs count as equal to each other. That is different from WHERE, where NULL = NULL is unknown. So SELECT DISTINCT city returns a single NULL row even if many customers have no city.

Text comparison is exact: 'ann@x.com' and 'Ann@x.com ' are different. Normalise with lower() and trim() in both queries if they should match.

The cost of removing duplicates

To remove duplicates, Postgres must compare every row with every other, which it does by sorting or by building a hash table of all rows. On millions of rows that costs real time and memory.

UNION ALL skips this work and simply appends the second result after the first. If the two queries cannot overlap, for example orders_2025 and orders_2026, UNION ALL gives the same answer far more cheaply.

INTERSECT ALL and EXCEPT ALL exist too. They keep duplicates by counting: if a value appears 3 times on the left and once on the right, EXCEPT ALL returns it twice.

  • UNION = UNION ALL + remove duplicates
  • Know the inputs cannot overlap? Use UNION ALL
  • EXCEPT ALL subtracts counts, not just presence

Sorting and limiting a combined result

ORDER BY and LIMIT at the end apply to the whole combined result, not to the last query. To sort or limit each part separately, wrap the part in brackets: (SELECT ... ORDER BY score DESC LIMIT 3) UNION ALL (SELECT ...).

Because column names come from the first query, ORDER BY should use those names or column numbers. A common trick is to add a constant column such as 'customer' AS source to each part so you can tell later which query each row came from.

CompareWhere ORDER BY and LIMIT apply
At the very end
  • Applies to the whole combined result
  • Uses the first query's column names
  • One sort for everything
Inside brackets
  • (SELECT ... ORDER BY score DESC LIMIT 3)
  • Limits each part separately
  • Then UNION ALL the parts

DISTINCT ON: a Postgres favourite

DISTINCT ON (customer_id) keeps only the first row for each customer_id, where "first" is decided by ORDER BY. For example, SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, ordered_at DESC returns each customer's latest order.

The ORDER BY must start with the same columns as DISTINCT ON. The remaining ORDER BY columns choose which row wins. It is a short, readable alternative to a window function for "latest row per group" questions.

FlowDISTINCT ON: latest order per customer
  1. Step 1
    ORDER BY customer_id, ordered_at DESC

    Newest first inside each customer

  2. Step 2
    Group by customer_id

    Rows with the same DISTINCT ON value

  3. Step 3
    Keep the first row

    The newest order wins

  4. Step 4
    Result

    One row per customer

Learn it in 3 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Combine results with UNION and UNION ALL~30m
  2. 2
    Compare sets with INTERSECT and EXCEPT~30m
  3. 3
    Deduplicate with DISTINCT~30m

Key points

  • Both queries need the same column count and compatible types.
  • Column names come from the first query.
  • Prefer UNION ALL unless you really need duplicates removed.
  • DISTINCT removes duplicate rows from a single query's output.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
-- everyone to email: customers and newsletter subscribers
SELECT email FROM customers
UNION
SELECT email FROM subscribers;

-- subscribers who never bought anything
SELECT email FROM subscribers
EXCEPT
SELECT email FROM customers;

SELECT DISTINCT country FROM customers ORDER BY country;

One activity feed from three tables

An admin page shows recent sign-ups, orders and reviews in one list. Step 1: write one query per table that returns the same three columns: when, kind, detail. Step 2: give the kind column a fixed label in each part. Step 3: join them with UNION ALL because rows from different tables cannot be duplicates. Step 4: sort and limit the combined result once at the end.

sql
SELECT created_at AS at, 'signup' AS kind, email AS detail FROM users
UNION ALL
SELECT ordered_at, 'order', 'order #' || id FROM orders
UNION ALL
SELECT created_at, 'review', left(body, 40) FROM reviews
ORDER BY at DESC
LIMIT 20;

Checking that a data migration lost nothing

You copied customers from an old system into a new table. Step 1: old EXCEPT new lists rows that did not arrive. Step 2: new EXCEPT old lists rows that changed or appeared from nowhere. Step 3: both should return zero rows. Comparing the chosen columns this way finds missing rows and silently altered values, which a simple COUNT(*) comparison would miss.

sql
SELECT id, email, country FROM old_customers
EXCEPT
SELECT id, email, country FROM customers;

SELECT id, email, country FROM customers
EXCEPT
SELECT id, email, country FROM old_customers;

Quick reference

  • A UNION B: rows in either (no duplicates). UNION ALL: everything, faster
  • A INTERSECT B: rows in both. A EXCEPT B: rows in A only
  • Same number of columns, same order, compatible types; names come from A
  • ORDER BY / LIMIT at the end apply to the combined result
  • Add 'label' AS source to each part to know where a row came from
  • SELECT DISTINCT ON (key) ... ORDER BY key, ts DESC: latest row per key
  • Set operations treat NULLs as equal to each other

Common mistakes

  • Using UNION when UNION ALL is meant, paying for an unneeded sort or hash.
  • Mismatched column order, so values land under the wrong heading.
  • Using DISTINCT to hide duplicate rows caused by a bad join.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Query A returns 5 rows and B returns 3 rows, 2 of them identical to rows in A. How many rows does A UNION ALL B return?

Question 2

2Same data: how many rows does A UNION B return (A has no internal duplicates)?

Question 3

3Which query finds customers who bought in 2025 but not in 2026?

Question 4

4What does SELECT DISTINCT ON (user_id) * FROM logins ORDER BY user_id, at DESC return?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    List every distinct country that appears in either customers(country) or suppliers(country).

  2. Exercise 2medium

    Find product ids that were ordered in both January and February 2026, using order_items(product_id) and orders(ordered_at).

  3. Exercise 3hard

    Show the top 3 products by price from category 'books' and the top 3 from 'games' in one result, each part sorted separately.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why is UNION slower than UNION ALL?
UNION has to find and remove duplicate rows, which needs a sort or a hash over all rows. UNION ALL just appends the results.
Can I UNION two tables with different column names?
Yes. Only the number and types of columns must match. The result uses the column names from the first query.
Is EXCEPT the same as NOT IN?
Close, but EXCEPT compares whole rows, removes duplicates, and treats NULLs as equal. NOT IN behaves badly when the list contains NULL, so EXCEPT or NOT EXISTS is usually safer.

Go deeper

ShareXLinkedInWhatsApp