What is the difference between UNION and UNION ALL?

后端 未结 26 3061
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 11:28

What is the difference between UNION and UNION ALL?

26条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 12:06

    UNION - results in distinct records

    while

    UNION ALL - results in all the records including duplicates.

    Both are blocking operators and hence I personally prefer using JOINS over Blocking Operators(UNION, INTERSECT, UNION ALL etc. ) anytime.

    To illustrate why Union operation performs poorly in comparison to Union All checkout the following example.

    CREATE TABLE #T1 (data VARCHAR(10))
    
    INSERT INTO #T1
    SELECT 'abc'
    UNION ALL
    SELECT 'bcd'
    UNION ALL
    SELECT 'cde'
    UNION ALL
    SELECT 'def'
    UNION ALL
    SELECT 'efg'
    
    
    CREATE TABLE #T2 (data VARCHAR(10))
    
    INSERT INTO #T2
    SELECT 'abc'
    UNION ALL
    SELECT 'cde'
    UNION ALL
    SELECT 'efg'
    

    Following are results of UNION ALL and UNION operations.

    A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

    Using UNION results in Distinct Sort operations in the Execution Plan. Proof to prove this statement is shown below:

提交回复
热议问题