Interview Q&A · SQL · 10 questions in this topic

UNION, INTERSECT & EXCEPT — SQL Interview Q&A

All SQL topics

Combining result sets — set operators, duplicate semantics, and UNION vs JOIN judgment. Part of Set Operations · 192 questions in the SQL bank.

How do UNION and UNION ALL differ?

Answer

UNION merges result sets and removes duplicates (sort/hash pass — costs). UNION ALL keeps everything including duplicates (fast, no dedup). Default to UNION ALL unless dedup is the requirement — paying sort costs for unwanted dedup is the classic waste.

Both require identical column counts with compatible types.

Example

Example.sqlsql
SELECT email FROM customers
UNION ALL            -- fast: keeps dupes
SELECT email FROM leads;

💡 UNION ALL by default is the performance-minded habit.

What must UNION inputs share (columns, types, order)?

Answer

Same column count, pairwise-compatible types (implicit casts where defined), with column names taken from the first branch. ORDER BY/LIMIT apply to the whole union (at the end, referencing first-branch names) — per-branch ordering needs parenthesized subqueries.

Type mismatches (INT vs TEXT) error or cast unpredictably per engine — align explicitly with CASTs.

Example

Example.sqlsql
(SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3)
UNION ALL
(SELECT head AS name, NULL AS salary FROM departments);

💡 First-branch names rule the output is the detail that answers alias questions.

How do INTERSECT and EXCEPT work?

Answer

INTERSECT returns rows present in both sets (set AND). EXCEPT returns rows in the first but not the second (set difference). Both dedup like UNION (ALL variants keep duplicates where supported). EXCEPT is order-sensitive (A EXCEPT B ≠ B EXCEPT A).

Common uses: permission overlap (INTERSECT), churn/orphans (EXCEPT), before-after diffs.

Example

Example.sqlsql
-- customers who are also leads:
SELECT email FROM customers
INTERSECT
SELECT email FROM leads;
-- customers who never ordered:
SELECT id FROM customers
EXCEPT
SELECT customer_id FROM orders;

💡 INTERSECT for overlap, EXCEPT for missing — the use-case pairing.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits