I am not asking difference between them, my question is when we need to use "Union All" ?
You would use UNION ALL when you really do need the multiple 'copies' of rows that would otherwise be removed when using UNION. It can also be faster on the query end, since the DB engine does not need to determine what are duplicates between the result sets.
When we do not need to exclude duplicated rows from recordset
- UNION will remove duplicates
- UNION ALL does not remove duplicates
Example
SELECT 1 AS foo
UNION
SELECT 1 AS foo
= one row
SELECT 1 AS foo
UNION ALL
SELECT 1 AS foo
= two rows
When you need to use them depends on your requirements. The difference between UNION and UNION ALL is that UNION ALL doesn't remove duplicate rows.
Union all
is used to join multiple data set into a single data set but it does not remove duplicates
You use UNION ALL to concatenate (append) two result sets into a single result set when they have the same columns (number and type).
An example will make it clear:
mysql> select * from tmp1;
+------+
| a |
+------+
| foo1 |
| foo2 |
+------+
2 rows in set (0.00 sec)
mysql> select * from tmp2;
+------+
| a |
+------+
| foo2 |
| foo3 |
| foo4 |
+------+
3 rows in set (0.00 sec)
mysql> select * from tmp1 union select * from tmp2;
+------+
| a |
+------+
| foo1 |
| foo2 | # DUPLICATES REMOVED.
| foo3 |
| foo4 |
+------+
4 rows in set (0.00 sec)
mysql> select * from tmp1 union all select * from tmp2;
+------+
| a |
+------+
| foo1 |
| foo2 |
| foo2 | # DUPLICATES NOT REMOVED.
| foo3 |
| foo4 |
+------+
5 rows in set (0.00 sec)
Coming to the question of When to use UNION ALL?
If you don't care that result set has duplicate rows or if you know there won't be any duplicates then use UNION ALL
instead of UNION
.
Why Union
or Union all
?
Ans: If you are looking some data from two or more different tables (I mean, by relationally) then you can use it.
Because the result will be a table, and every table should have a key, and UNION
ensures unique rows, you should in theory always use UNION
. However, because UNION ALL
does not ensure unique rows, UNION ALL
can perform better and therefore may be preferred in practise if you can be sure that both tables already contain unique rows.
The same logic applies to the choice between SELECT DISTINCT
and SELECT ALL
, BTW.