Column Count and Type Compatibility
The rules result sets must satisfy to be combined and common mismatch errors.
The Compatibility Rules Interviewers Probe
Every set operation (UNION, INTERSECT, EXCEPT) requires the two result sets to be union-compatible. Interviewers ask this to see if you know the silent ways these queries break.
Two rules govern compatibility: matching column count and compatible data types position by position. Get either wrong and you get an error or a surprising result.
Rule 1: Same Number of Columns
Both queries must project the same number of columns. If the first query returns three columns and the second returns two, the database rejects the statement.
This is the single most common set-operation error in interviews, especially after someone edits one branch and forgets the other.
SELECT id, name, city FROM a
UNION
SELECT id, name FROM b;
-- ERROR: each UNION query must have the same number of columnsAll lessons in this course
- UNION vs UNION ALL
- Column Count and Type Compatibility
- INTERSECT and EXCEPT for Comparison
- Emulating Set Operations With Joins