What is the difference between UNION and UNION ALL?

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

What is the difference between UNION and UNION ALL?

26条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 11:58

    Suppose that you have two table Teacher & Student

    Both have 4 Column with different Name like this

    Teacher - ID(int), Name(varchar(50)), Address(varchar(50)), PositionID(varchar(50))
    

    Student- ID(int), Name(varchar(50)), Email(varchar(50)), PositionID(int)
    

    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 this

    SELECT * FROM Student
    UNION
    SELECT * FROM Teacher
    

    the 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 this

    SELECT * FROM Student
    UNION ALL
    SELECT * FROM Teacher
    

    Output

    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

提交回复
热议问题