What does UNION do? What is the difference between UNION and UNION ALL? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 12

What does UNION do? What is the difference between UNION and UNION ALL?


9th Oct 2018, 3:08 AM
Kristel Apolinar
Kristel Apolinar - avatar
6 Answers
+ 5
UNION combines multiple datasets into a single dataset, and removes any existing duplicates. UNION ALL combines multiple datasets into one dataset, but does not remove duplicate rows.
9th Oct 2018, 8:56 AM
Florian Hähnert
+ 3
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). 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)
10th Oct 2018, 8:39 PM
Yahia Baiba
Yahia Baiba - avatar
+ 1
That is also explained in a lesson below: https://www.sololearn.com/learn/SQL/1867/
9th Oct 2018, 7:13 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
Union removes duplicate records but union all does not.
29th Mar 2019, 9:01 AM
Yugyn Dprodigy
Yugyn Dprodigy - avatar
+ 1
UNION ALL is faster than UNION, as it does not perform the duplicate removal operation over the data set. Union removes existing any existing duplicate while Union All does not remove duplicate.
30th May 2020, 9:57 PM
union is merge result sets of two or more SELECT statements,union all is allow duplicate values
31st Oct 2018, 2:40 AM
Cymzug - avatar