What is the difference between UNION and UNION ALL?

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

What is the difference between UNION and UNION ALL?

相关标签:
26条回答
  • 2020-11-21 12:00

    Important! Difference between Oracle and Mysql: Let's say that t1 t2 don't have duplicate rows between them but they have duplicate rows individual. Example: t1 has sales from 2017 and t2 from 2018

    SELECT T1.YEAR, T1.PRODUCT FROM T1
    
    UNION ALL
    
    SELECT T2.YEAR, T2.PRODUCT FROM T2
    

    In ORACLE UNION ALL fetches all rows from both tables. The same will occur in MySQL.

    However:

    SELECT T1.YEAR, T1.PRODUCT FROM T1
    
    UNION
    
    SELECT T2.YEAR, T2.PRODUCT FROM T2
    

    In ORACLE, UNION fetches all rows from both tables because there are no duplicate values between t1 and t2. On the other hand in MySQL the resultset will have fewer rows because there will be duplicate rows within table t1 and also within table t2!

    0 讨论(0)
  • 2020-11-21 12:00

    The only difference is :

    "UNION" removes duplicate rows.

    "UNION ALL" does not remove duplicate rows.

    0 讨论(0)
  • 2020-11-21 12:00

    UNION ALL also works on more data types as well. For example when trying to union spatial data types. For example:

    select a.SHAPE from tableA a
    union
    select b.SHAPE from tableB b
    

    will throw

    The data type geometry cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable.

    However union all will not.

    0 讨论(0)
  • 2020-11-21 12:03

    In ORACLE: UNION does not support BLOB (or CLOB) column types, UNION ALL does.

    0 讨论(0)
  • 2020-11-21 12:03

    It is good to understand with a Venn diagramm.

    here is the link to the source. There is a good description.

    0 讨论(0)
  • 2020-11-21 12:03

    In very simple words the difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL will include duplicate records.

    0 讨论(0)
提交回复
热议问题