SpinTheMic
Pro

SQL · Beginner

What is the difference between UNION and UNION ALL?

By Anurag Pandey, Lead Data Engineer ·

The short answer

Both stack the results of two queries. UNION removes duplicate rows, which costs extra work; UNION ALL keeps every row and is faster. Both need the same number of columns with compatible types.

Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Say it like this

About 50 seconds out loud. Use it as a model, then put it in your own words.

Both combine the results of two SELECT statements into one result, stacked on top of each other. The difference is duplicates. UNION removes duplicate rows from the combined result, which means the database has to sort or hash all the rows to find them. UNION ALL keeps every row, including duplicates, so it's cheaper and faster. For both, the queries need the same number of columns, in the same order, with compatible data types, and the column names come from the first query. My default is UNION ALL. If I'm combining data from two regions that can't overlap, there's nothing to remove, so UNION would just add cost. I use UNION only when I really need duplicates removed, and I say so in a comment.

What interviewers look for

  • You explain duplicate removal and its cost.
  • You know the column rules for combining queries.
  • You choose UNION ALL by default and explain why.

Common mistakes

  • Saying UNION removes duplicates only between the two queries. It also removes them within each.
  • Using UNION by habit when the inputs cannot overlap.
  • Thinking columns are matched by name rather than by position.

Follow-up questions to expect

  1. 1How are columns matched in a UNION?
  2. 2What do INTERSECT and EXCEPT do?
  3. 3How would you combine two tables that have different columns?
Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Checked against

All interview question guides