Difference Between Union and Union All in SQL

UNION & UNION ALL:

1. UNION, UNION ALL both merge 2 tables or 2 query results into a single temporary table. The 2 tables must have same structure, otherwise sql returns error.
2. The main difference is UNION will remove duplicate records from results, where as UNION ALL will include duplicate records too.
3. The other difference is, UNION ALL is typically better than UNION, since UNION requires Database server to do the additional work of removing any duplicates. So, when it is certain that there will not be any duplicates in the 2 tables or having duplicates is not a problem, use UNION ALL for better performance.

Comments