Interview Q&A · SQL · 10 questions in this topic
UNION, INTERSECT & EXCEPT — SQL Interview Q&A
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
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
(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
-- 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.
UNION vs JOIN — how do you choose?
Answer
UNION stacks same-shaped results vertically (more rows, same columns) — combining cohorts, logs, snapshots. JOIN widens rows horizontally (more columns, matched rows) — combining entities. Shape of the question decides: same-kind lists UNION; related entities JOIN.
Dimensional check: UNION needs column compatibility; JOIN needs key relationships.
Example
-- same-shaped lists: UNION -- SELECT email FROM customers UNION ALL SELECT email FROM leads; -- related entities: JOIN -- SELECT c.name, o.total FROM customers c JOIN orders o ...
💡 UNION lengthens, JOIN widens — the dimensional mantra (same as the joins section).
How do set operators treat NULLs and duplicates?
Answer
Set operators compare whole rows with NULLs considered equal to each other (unlike WHERE) — NULL rows dedup together. UNION/INTERSECT/EXCEPT dedup; ALL variants preserve duplicates including repeated NULL rows.
NULL-equality in set ops vs UNKNOWN in predicates is the contrast to articulate.
Example
-- (NULL, 1) UNION (NULL, 1) yields ONE row: NULLs match here
💡 NULLs-equal-in-sets vs NULLs-unknown-in-WHERE is the deep-cut contrast.
How do you paginate or sort a UNION result?
Answer
ORDER BY/LIMIT attach once at the end over the combined set, using first-branch column names/positions. Per-branch limits need parenthesized branches. Keyset pagination over unions needs a synthetic sort key carried through every branch.
UNION inside a subquery/CTE then outer ORDER BY is the composable form.
Example
SELECT name, salary FROM employees UNION ALL SELECT head, NULL FROM departments ORDER BY salary DESC NULLS LAST LIMIT 10;
How do you find rows in A but not B efficiently at scale (EXCEPT vs alternatives)?
Answer
NOT EXISTS anti-join usually beats EXCEPT on huge sets (stops at first match, leverages indexes, NULL-safe). LEFT JOIN/IS NULL is planner-competitive. EXCEPT is clearest for small exact set-diffs and snapshot comparisons.
Choose by scale and NULL-safety: EXCEPT for clarity on modest sets, NOT EXISTS for production anti-joins.
Example
-- production anti-join (NULL-safe, index-friendly): SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
💡 EXCEPT for diffs, NOT EXISTS for scale is the selection rule.
Can you UNION tables with different meanings (type-tagged unions)?
Answer
Yes — pad missing columns with NULLs/casts, add a literal source tag per branch, and keep one combined ORDER BY. The tag column preserves provenance (which branch each row came from) for downstream CASE logic.
Activity feeds, audit trails and search-across-entities all use tagged unions.
Example
SELECT id, name, 'emp' AS kind FROM employees UNION ALL SELECT dept_id, head, 'dept' FROM departments ORDER BY name;
💡 Literal tag column is the provenance pattern to name.
What are the performance characteristics of UNION chains?
Answer
Each branch executes (ideally with its own index), then results merge with a dedup pass for plain UNION (the expensive step — sort/unique over the combined set). UNION ALL skips dedup entirely. Push filters into branches (not just outside) so each scans less.
Filter-in-branch plus UNION ALL is the fast shape; bare UNION over huge branches is the slow one.
Key points
- 1Branches — indexed separately, filter inside.
- 2Merge — dedup pass only for plain UNION.
- 3ALL — no dedup, near sum-of-branches cost.
Does MySQL support INTERSECT and EXCEPT?
Answer
MySQL 8.0.31+ supports INTERSECT and EXCEPT (older versions do not — rewrite with INNER JOIN / NOT EXISTS). MariaDB supports EXCEPT but not INTERSECT. Portable code prefers JOIN/EXISTS forms that run everywhere.
Version-gated features are why portable SQL favors the oldest sufficient construct.
Example
-- portable INTERSECT (any engine): SELECT DISTINCT a.email FROM a INNER JOIN b ON b.email = a.email;
💡 Portable rewrites beat version-gated syntax in shared codebases.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission