What is the difference between UNION and UNION ALL?

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

What is the difference between UNION and UNION ALL?

26条回答
  •  无人共我
    2020-11-21 11:53

    (From Microsoft SQL Server Book Online)

    UNION [ALL]

    Specifies that multiple result sets are to be combined and returned as a single result set.

    ALL

    Incorporates all rows into the results. This includes duplicates. If not specified, duplicate rows are removed.

    UNION will take too long as a duplicate rows finding like DISTINCT is applied on the results.

    SELECT * FROM Table1
    UNION
    SELECT * FROM Table2
    

    is equivalent of:

    SELECT DISTINCT * FROM (
        SELECT * FROM Table1
        UNION ALL
        SELECT * FROM Table2) DT
    

    A side effect of applying DISTINCT over results is a sorting operation on results.

    UNION ALL results will be shown as arbitrary order on results But UNION results will be shown as ORDER BY 1, 2, 3, ..., n (n = column number of Tables) applied on results. You can see this side effect when you don't have any duplicate row.

提交回复
热议问题