What is the difference between UNION
and UNION ALL
?
Important! Difference between Oracle and Mysql: Let's say that t1 t2 don't have duplicate rows between them but they have duplicate rows individual. Example: t1 has sales from 2017 and t2 from 2018
SELECT T1.YEAR, T1.PRODUCT FROM T1
UNION ALL
SELECT T2.YEAR, T2.PRODUCT FROM T2
In ORACLE UNION ALL fetches all rows from both tables. The same will occur in MySQL.
However:
SELECT T1.YEAR, T1.PRODUCT FROM T1
UNION
SELECT T2.YEAR, T2.PRODUCT FROM T2
In ORACLE, UNION fetches all rows from both tables because there are no duplicate values between t1 and t2. On the other hand in MySQL the resultset will have fewer rows because there will be duplicate rows within table t1 and also within table t2!
The only difference is :
"UNION" removes duplicate rows.
"UNION ALL" does not remove duplicate rows.
UNION ALL
also works on more data types as well. For example when trying to union spatial data types. For example:
select a.SHAPE from tableA a
union
select b.SHAPE from tableB b
will throw
The data type geometry cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable.
However union all
will not.
In ORACLE: UNION does not support BLOB (or CLOB) column types, UNION ALL does.
It is good to understand with a Venn diagramm.
here is the link to the source. There is a good description.
In very simple words the difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL will include duplicate records.