What is the difference between UNION and UNION ALL, and how would you test either result?
Answer
UNION combines compatible result sets and removes duplicate rows, while UNION ALL keeps every row and normally avoids the duplicate-removal work. Both sides must return compatible column counts and types, but column names and ordering still need deliberate handling. Tests should include duplicates within and across inputs, NULL values, empty inputs, type conversions, ordering applied only at the final result and reconciliation of expected row counts.
Strong answer includes
- distinguishes duplicate removal from retention
- mentions compatible result shapes
- tests nulls, empty inputs and row-count reconciliation
Practical example
Runs against the resettable SQLite sample database used by the playground.
Run the query to see the result.
UNION performs duplicate elimination across the combined result. UNION ALL preserves multiplicity and is usually cheaper when duplicate removal is not part of the requirement.
Expected result: UNION may return fewer rows than UNION ALL when the inputs overlap.