Difference between UNION and UNION ALL in SQL
Both UNION
and UNION ALL
are used to combine the result sets of two or more SELECT
queries. For both operators, the number of columns, data types of columns, and the order of columns must be the same in the SELECT
clause. The ORDER BY
clause, if used, must be applied to the last SELECT
statement.
UNION UNION ALL
Removes duplicate rows from the result set. Does not remove duplicate rows; all rows are returned.
Generally slower than UNION ALL
because it involves sorting and duplicate removal. Generally faster than UNION
as it does not perform duplicate removal.
When you need a combined list of unique records. When you need all records (including duplicates) and performance is critical.
Top comments (0)