Union — SQL Technical Interview Questions & Answers

Union

Union

  • UNION stacks results. SELECT name FROM y2024 UNION SELECT name FROM y2025; Unique names from both years. Column count must match. UNION ALL keeps duplicates and is cheaper.
  • ORDER BY after the last SELECT, in brackets if needed. Types should be compatible (both names, not name vs marks).
  • Trap: UNION when you needed JOIN. Trap: UNION ALL vs UNION mixed up in a viva.
  • On the example next to this theory: UNION merges result sets and drops duplicate rows.

Technical Interview Tip: SELECT name FROM y2024 UNION SELECT name FROM y2025;

Code Examples for Union

Union — sample query

CREATE TABLE a (id INTEGER, label TEXT);
CREATE TABLE b (id INTEGER, label TEXT);
INSERT INTO a VALUES (1, 'x'), (2, 'y');
INSERT INTO b VALUES (2, 'y'), (3, 'z');
SELECT label FROM a
UNION
SELECT label FROM b;

UNION merges result sets and drops duplicate rows.

How to Explain Union to an Interviewer

UNION vs UNION ALL?

UNION distinct UNION ALL keeps duplicates, faster