Question presented to candidate: "We collect leads from the website and from events, in two tables. I want one combined list. Should I use UNION or UNION ALL, what exactly is the difference, and what does it cost?"
What a strong answer should cover:
- Both stack the rows of two queries with the same number of columns;
UNION ALLkeeps every row,UNIONremoves duplicate rows from the combined result - Duplicates are whole rows (every column compared), they are removed within a branch too, and two NULLs count as equal for this purpose
- The cost:
UNIONmust sort or hash the whole result to find duplicates (PostgreSQL shows aHashAggregateorUniqueoverAppend);UNION ALLjust appends and can stream - Rules: column count must match, types must be compatible (PostgreSQL is strict, SQLite is not), column names come from the first branch, one
ORDER BYat the end applies to the whole result - Default to
UNION ALLwhen the branches cannot overlap or duplicates are wanted; useUNIONonly when you really need distinct rows - The relatives:
INTERSECTandEXCEPT(and theirALLforms in PostgreSQL)
Code / implementation expected: Optional β the same two queries combined both ways, with row counts.
Schema used by the examples: