Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance of union versus union all

Tags:

I have to run a select statement across several tables. I am sure the tables return different records. I am anyway using UNION ALL.

Is it better to use UNION or of UNION ALL in performance terms when I am sure the tables return different records?

like image 240
LaBracca Avatar asked Sep 02 '10 14:09

LaBracca


People also ask

Which has better performance UNION or UNION all?

UNION retrieves only distinct records from all queries or tables, whereas UNION ALL returns all the records retrieved by queries. Performance of UNION ALL is higher than UNION.

Why UNION all is better than UNION?

UNION ALL keeps all of the records from each of the original data sets, UNION removes any duplicate records. UNION first performs a sorting operation and eliminates of the records that are duplicated across all columns before finally returning the combined data set.

What is the biggest difference between UNION and UNION all?

The only difference between Union and Union All is that Union extracts the rows that are being specified in the query while Union All extracts all the rows including the duplicates (repeated values) from both the queries.

When should you use UNION as opposed to UNION all?

When comparing UNION vs. UNION ALL , there is one major difference: UNION only returns unique. UNION ALL returns all records, including duplicates.


2 Answers

UNION ALL will perform better than UNION when you're not concerned about eliminating duplicate records because you're avoiding an expensive distinct sort operation. See: SQL SERVER – Difference Between Union vs. Union All – Optimal Performance Comparison

like image 179
Joe Stefanelli Avatar answered Oct 25 '22 21:10

Joe Stefanelli


UNION ALL always is faster, because UNION exclude duplicated entries

like image 42
Michael Pakhantsov Avatar answered Oct 25 '22 20:10

Michael Pakhantsov