Java Zero to All All questionsPractise free
Interview questions › Databases & Persistence › SQL Mastery & Joins

What's the difference between UNION and UNION ALL, and why does it matter for performance?

Level I · BeginnerSQL Mastery & Joins
Short answer

UNION combines two result sets and removes duplicate rows, which forces the database to sort or hash the entire combined set to deduplicate; UNION ALL simply concatenates and keeps duplicates.

Explanation

If you know the sets are disjoint or duplicates are acceptable, always use UNION ALL because it skips the expensive dedup step and can stream results. Using UNION out of habit when UNION ALL would do is a common, easily fixed performance leak on large result sets.

Common mistakes
  • Using UNION when duplicates are impossible, paying for a sort.
  • Not knowing UNION removes duplicates.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for SQL Mastery & Joins.

Practise free

More on SQL Mastery & Joins