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 and UNION ALL used to combine two or more query results.
UNION command selects distinct and related information from two tables which will eliminates duplicate rows.
On the other hand, UNION ALL command selects all the values from both the tables, which displays all rows.
union is used to select distinct values from two tables where as union all is used to select all values including duplicates from the tables
Difference Between Union Vs Union ALL In Sql
What Is Union In SQL?
The UNION operator is used to combine the result-set of two or more data set .
Union Vs Union All With Example
UNION
merges the contents of two structurally-compatible tables into a single combined table.The difference between
UNION
andUNION ALL
is thatUNION will
omit duplicate records whereasUNION ALL
will include duplicate records.Union
Result set is sorted in ascending order whereasUNION ALL
Result set is not sortedUNION
performs aDISTINCT
on its Result set so it will eliminate any duplicate rows. WhereasUNION ALL
won't remove duplicates and therefore it is faster thanUNION
.*Note: The performance of
UNION ALL
will typically be better thanUNION
, sinceUNION
requires the server to do the additional work of removing any duplicates. So, in cases where it is certain that there will not be any duplicates, or where having duplicates is not a problem, use ofUNION ALL
would be recommended for performance reasons.I add an example,
UNION, it is merging with distinct --> slower, because it need comparing (In Oracle SQL developer, choose query, press F10 to see cost analysis).
UNION ALL, it is merging without distinct --> faster.
and