Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To union or union all, that is the question

I have two queries that I'm UNIONing together such that I already know there will be no duplicate elements between the two queries. Therefore, UNION and UNION ALL will produce the same results.

Which one should I use?

like image 466
Billy ONeal Avatar asked Oct 11 '10 20:10

Billy ONeal


1 Answers

You should use the one that matches the intent of what you are looking for. If you want to ensure that there are no duplicates use UNION, otherwise use UNION ALL. Just because your data will produce the same results right now doesn't mean that it always will.

That said, UNION ALL will be faster on any sane database implementation, see the articles below for examples. But typically, they are the same except that UNION performs an extra step to remove identical rows (as one might expect), and it may tend to dominate execution time.

  • SQL Server article
  • Oracle article
  • MySQL article
  • DB2 documentation
like image 119
Daniel DiPaolo Avatar answered Sep 30 '22 22:09

Daniel DiPaolo