How would you merge the results of two tables without duplicates?

Instruction: Explain the SQL query you would write to combine the results of two tables, ensuring no duplicates are present in the final result.

Context: This question tests the candidate's knowledge of SQL's set operations, focusing on their ability to efficiently merge data while maintaining data integrity.

Updated

Official answer

UNION combines two query results and removes duplicate result rows. UNION ALL preserves every occurrence. Both require the same number of output columns with compatible types; the column names need not match.

For PostgreSQL:

SELECT id FROM (VALUES (1), (1), (NULL::integer)) AS a(id)
UNION
SELECT id FROM (VALUES (1), (2), (NULL::integer)) AS b(id)
ORDER BY id NULLS LAST;

This returns 1, 2 and one NULL. Changing UNION to UNION ALL returns three 1s, one 2 and two NULLs. Deduplication compares the whole selected row, so selecting an additional differing column can preserve rows with the same ID.

Use UNION ALL when every event should be retained or overlap is known to be irrelevant. Use UNION when unique result rows are required. Deduplication has a cost, but correctness determines the choice. Neither operation changes the source tables or enforces their integrity. Only the outer ORDER BY guarantees result order.

Related Questions