Sobes.tech
Junior — Middle

How does using UNION differ from UNION ALL when combining queries in SQL?

sobes.tech AI

Answer from AI

UNION and UNION ALL are used to combine the results of two or more SQL queries, but there is an important difference between them:

  • UNION combines the results and automatically removes duplicates, returning only unique rows. This involves an additional sorting and comparison operation, which can slow down execution.

  • UNION ALL combines the results without removing duplicates, returning all rows from all queries, including repetitions. This is faster because it does not require additional processing.

Example:

SELECT column1 FROM table1
UNION
SELECT column1 FROM table2;

-- returns unique values of column1 from both tables

SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;

-- returns all values, including duplicates