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#
from http://zengin.wordpress.com/2007/07/31/union-vs-union-all/
It is good to understand with a Venn diagramm.
here is the link to the source. There is a good description.
Suppose that you have two table Teacher & Student
Both have 4 Column with different Name like this
You can apply UNION or UNION ALL for those two table which have same number of columns. But they have different name or data type.
When you apply
UNION
operation on 2 tables, it neglects all duplicate entries(all columns value of row in a table is same of another table). Like thisthe result will be
When you apply
UNION ALL
operation on 2 tables, it returns all entries with duplicate(if there is any difference between any column value of a row in 2 tables). Like thisOutput
Performance:
Obviously UNION ALL performance is better that UNION as they do additional task to remove the duplicate values. You can check that from Execution Estimated Time by press ctrl+L at MSSQL
If there is no
ORDER BY
, aUNION ALL
may bring rows back as it goes, whereas aUNION
would make you wait until the very end of the query before giving you the whole result set at once. This can make a difference in a time-out situation - aUNION ALL
keeps the connection alive, as it were.So if you have a time-out issue, and there's no sorting, and duplicates aren't an issue,
UNION ALL
may be rather helpful.UNION
andUNION ALL
should work on all SQL Servers.You should avoid of unnecessary
UNION
s they are huge performance leak. As a rule of thumb useUNION ALL
if you are not sure which to use.UNION
The
UNION
command is used to select related information from two tables, much like theJOIN
command. However, when using theUNION
command all selected columns need to be of the same data type. WithUNION
, only distinct values are selected.UNION ALL
The
UNION ALL
command is equal to theUNION
command, except thatUNION ALL
selects all values.The difference between
Union
andUnion all
is thatUnion all
will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.A
UNION
statement effectively does aSELECT DISTINCT
on the results set. If you know that all the records returned are unique from your union, useUNION ALL
instead, it gives faster results.