Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between UNION and UNION ALL?

What is the difference between UNION and UNION ALL?

like image 801
Brian G Avatar asked Sep 08 '08 15:09

Brian G


People also ask

What is main 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.

Which is better UNION or UNION all?

UNION ALL is faster and more optimized than UNION. But we cannot use it in all scenarios. UNION ALL with SELECT DISTINCT is not equivalent to UNION.

What is the difference between UNION and UNION all which one is faster?

Both UNION and UNION ALL operators combine rows from result sets into a single result set. The UNION operator removes eliminate duplicate rows, whereas the UNION ALL operator does not. Because the UNION ALL operator does not remove duplicate rows, it runs faster than the UNION operator.


1 Answers

UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.

There is a performance hit when using UNION instead of UNION ALL, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).

To identify duplicates, records must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text fields to make short text fields for comparison (MS Jet), or may refuse to compare binary fields (ORACLE)

UNION Example:

SELECT 'foo' AS bar UNION SELECT 'foo' AS bar 

Result:

+-----+ | bar | +-----+ | foo | +-----+ 1 row in set (0.00 sec) 

UNION ALL example:

SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar 

Result:

+-----+ | bar | +-----+ | foo | | foo | +-----+ 2 rows in set (0.00 sec) 
like image 90
9 revs, 7 users 64% Avatar answered Oct 12 '22 14:10

9 revs, 7 users 64%