What is the UNION operator in SQL?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid MySQL / SQL basics — a prerequisite for any developer role.
Answer
UNION combines the result sets of two or more SELECT statements into a single result set. Rules: (1) Each SELECT must have the same number of columns; (2) Corresponding columns must have compatible data types; (3) Column names in the result come from the first SELECT. UNION automatically removes duplicate rows (like DISTINCT). UNION ALL keeps all rows including duplicates — faster because it skips the deduplication step. Use UNION ALL when you know there are no duplicates or don't need them removed. Example: SELECT id, name, "customer" AS type FROM customers UNION ALL SELECT id, name, "supplier" AS type FROM suppliers ORDER BY name; — note ORDER BY applies to the combined result. UNION vs JOIN: UNION stacks results vertically (more rows, same columns); JOIN combines results horizontally (same rows, more columns). Common use cases: combining similar data from multiple tables, combining historical and current data, implementing "find all X or Y" queries where a single table doesn't contain all the data.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.