runtime
26 / 88

lesson 26 Joins & sets · advanced

Combine sets with UNION

Combine query results with or without duplicates.

the idea

UNION stacks compatible query outputs and removes duplicate rows. UNION ALL retains duplicates. Both sides need the same number of columns in matching positions.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

customers4 columns · 8 rows
idinteger · keynametextcitytextjoined_attext
1AliceChicago2024-01-10
2BenAustin2024-02-12
3CaraSeattle2024-03-05
4DevChicago2024-04-20
5ElenaNULL2024-05-01

showing 5 of 8 rows

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT city
FROM customers
WHERE city='Chicago'
UNION
SELECT city
FROM customers
WHERE city='Austin';

Watch for: UNION combines rows vertically; JOIN combines columns horizontally.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Build two compatible city lists. Chicago and Austin rows each produce a city column. UNION stacks compatible selects and drops duplicates.

    step-1.sql
    SELECT city
    FROM customers
    WHERE city IN ('Chicago', 'Austin')
    ORDER BY city;
  2. Stack sets with UNION. UNION removes duplicates across the stacked rows. UNION ALL would keep every duplicate.

    step-2.sql
    SELECT city
    FROM customers
    WHERE city = 'Chicago'
    UNION
    SELECT city
    FROM customers
    WHERE city = 'Austin';

challenge 1

Return distinct city values from Chicago customers and Austin customers using UNION.

Return cityany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.