Junior — Middle
Explain how the UNION ALL operator works in SQL and how it differs from UNION.
sobes.tech AI
Answer from AI
The UNION ALL operator in SQL combines the results of two or more SELECT queries, returning all rows from all queries, including duplicates. Unlike UNION, which automatically removes duplicates and returns only unique rows, UNION ALL retains all records, making it faster as it does not require an additional operation to remove duplicates.
Example:
SELECT name FROM employees
UNION ALL
SELECT name FROM managers;
This query will return all names from the employees and managers tables, including duplicate names if they exist in both tables.
If UNION is used instead of UNION ALL, the final set will contain only unique names without duplicates.