DELAPARRA
Index
Color
NL
Category: SQL

UNION vs UNION ALL

Explained by Updated

What is UNION vs UNION ALL?

UNION vs UNION ALL: Both stack result sets. UNION removes duplicates (and pays for a sort/hash); UNION ALL keeps everything and is faster. UNION and UNION ALL stack the results of two queries into one list. Both queries must return the same number of columns with compatible types. The difference is duplicates. UNION removes duplicate rows, which requires sorting or hashing the whole result. UNION ALL keeps everything as it is, which makes it faster.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about UNION vs UNION ALL

What should you keep in mind with UNION vs UNION ALL?

Use UNION ALL by default, and only switch to UNION when you really need duplicates removed. If the two queries cannot overlap, for example active and archived orders from separate tables, UNION just does extra work for nothing. Add ORDER BY once at the end of the combined query; ordering inside each part is ignored or not allowed in most databases.

What does an example of UNION vs UNION ALL look like?

SELECT id FROM active UNION ALL SELECT id FROM archived;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with U

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.