Learn SQL
-- setops.union

UNION & UNION ALL in SQL

Stack result sets — with or without duplicates

--concept

UNION appends the rows of one query to another: SELECT … UNION SELECT …. Both queries must return the same number of columns with compatible types. Plain UNION removes duplicate rows across the combined result (a set operation); UNION ALL keeps everything, which is cheaper because no dedup pass runs. Rule of thumb: use UNION ALL unless you specifically need duplicates gone.

--how it works
1

Two queries, one shape

Each SELECT returns its own result — the column counts must match and types must be compatible row-by-row.

2

The engine stacks them

Rows of the second result are appended to the first; column names come from the first SELECT.

3

Dedup is the difference

UNION sorts/hashes the combined rows to remove duplicates; UNION ALL skips that pass and returns everything.

4

Order the combined result

ORDER BY / LIMIT after the last SELECT apply to the union as a whole — never to the individual branches.

5

Choose by intent

Need distinct options for a filter dropdown? UNION. Logging every event from two tables, duplicates allowed? UNION ALL.

--visualization
SELECT departmentFROM employees — 6 rowsEngineeringSalesEngineeringMarketingSalesEngineeringSELECT dept_idFROM departments — 3 rowsEngineeringSalesMarketingSELECT department FROM employees UNION SELECT dept_id FROM departments ORDER BY department;
survivor (first occurrence) duplicate removed (UNION)
Stage 1 / 4
Two SELECTs run: employees returns six department rows, departments returns three dept_id rows.
--example
query.sql
1SELECT department FROM employees
2UNION
3SELECT dept_id FROM departments
4ORDER BY department;
Result
department
Engineering
Marketing
Sales

Employees mention three departments, the departments table lists the same three — UNION collapses the nine raw rows into three distinct names. With UNION ALL you would get all nine rows back.

--variants

UNION — distinct departments

Six raw rows collapse to three distinct names.

query.sql
1SELECT department FROM employees
2UNION
3SELECT dept_id FROM departments
4ORDER BY department;
Result
department
Engineering
Marketing
Sales
1Employees mention Engineering ×3, Sales ×2, Marketing ×1; departments adds the same three names.
2The dedup pass (a sort or hash) keeps one row per value.
3Same result as SELECT DISTINCT over the combined rows — spelled by the operator.

UNION ALL — everything, fast

No dedup pass, so every row from both sides survives.

query.sql
1SELECT department FROM employees
2UNION ALL
3SELECT dept_id FROM departments
4ORDER BY department;
Result
department
Engineering
Engineering
Engineering
Engineering
Marketing
Marketing
Sales
Sales
Sales
13 + 3 department names and 3 dept_id rows — all 9 survive (duplicates included).
2The plan is a plain Append node — the cheapest set operation there is.
3When you will DISTINCT later, or duplicates are impossible by design, always pick UNION ALL.

Shape mismatch — compile error

Column counts must line up; the check happens before execution.

query.sql
1SELECT name, salary FROM employees
2UNION
3SELECT dept_id FROM departments;
Result
error
ERROR: each UNION query must have the same number of columns
1Two columns cannot stack onto one — the statement fails to plan.
2Pad with NULL or literal placeholders when a branch lacks a column: SELECT dept_id, NULL FROM departments.
3Type mismatches (date vs number) fail the same way — CAST one side to align.

Classic pattern — unified activity feed

Merge two event types into one chronological stream.

query.sql
1SELECT 'signup' AS kind, name AS label FROM employees WHERE age < 30
2UNION ALL
3SELECT 'raise', name || ' → ' || salary FROM employees WHERE salary > 80000
4ORDER BY kind, label;
Result
kindlabel
raiseAlice → 85000
raiseCynthia → 91000
signupElena
signupAlice
1Each branch shapes its rows to a common contract (kind, label) with a literal tag.
2UNION ALL keeps both streams complete; ORDER BY merges them for display.
3This feed/report pattern — tag + stack + sort — is everywhere in real systems.
--key facts
Dedup costsUNION sorts/hashes every row; UNION ALL just concatenates
Symmetric inputswap the two SELECTs and UNION result is identical
Same-shape rulecolumn count and types must line up — mismatch is a compile-time error
--use cases
Dropdown options assembled from several tables (UNION for distinct values)
Reporting periods: this month UNION last month, stacked then aggregated
Search across heterogeneous tables fed into one results list
ETL staging: append yesterday’s partition with UNION ALL, dedupe downstream
--under the hood
UNION’s dedup is a full sort or hash of the combined result — on big inputs it often dominates query cost.
Postgres also offers INTERSECT/EXCEPT with the same dedup semantics; MySQL historically lacks them — emulate with DISTINCT + JOINs.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.