What is the difference between UNION
and UNION ALL
?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- php PDO::FETCH_ASSOC doesnt detect select after ba
- Bulk update SQL Server C#
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 ofUNION 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:
Result:
UNION ALL example:
Result:
In ORACLE: UNION does not support BLOB (or CLOB) column types, UNION ALL does.
UNION
removes duplicates, whereasUNION ALL
does not.In order to remove duplicates the result set must be sorted, and this may have an impact on the performance of the UNION, depending on the volume of data being sorted, and the settings of various RDBMS parameters ( For Oracle
PGA_AGGREGATE_TARGET
withWORKAREA_SIZE_POLICY=AUTO
orSORT_AREA_SIZE
andSOR_AREA_RETAINED_SIZE
ifWORKAREA_SIZE_POLICY=MANUAL
).Basically, the sort is faster if it can be carried out in memory, but the same caveat about the volume of data applies.
Of course, if you need data returned without duplicates then you must use UNION, depending on the source of your data.
I would have commented on the first post to qualify the "is much less performant" comment, but have insufficient reputation (points) to do so.
Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.
UNION performs a DISTINCT on the result set, eliminating any duplicate rows.
UNION ALL does not remove duplicates, and it therefore faster than UNION.
Example: If we have two tables, 1) Employee and 2) Customer
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
In ORACLE UNION ALL fetches all rows from both tables. The same will occur in MySQL.
However:
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!
Just to add my two cents to the discussion here: one could understand the
UNION
operator as a pure, SET-oriented UNION - e.g. set A={2,4,6,8}, set B={1,2,3,4}, A UNION B = {1,2,3,4,6,8}When dealing with sets, you would not want numbers 2 and 4 appearing twice, as an element either is or is not in a set.
In the world of SQL, though, you might want to see all the elements from the two sets together in one "bag" {2,4,6,8,1,2,3,4}. And for this purpose T-SQL offers the operator
UNION ALL
.