What is the difference between UNION and UNION ALL?

UNIONUNION ALL什么区别?


UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.

There is a performance hit when using UNION instead of UNION ALL , since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).

UNION Example:

SELECT 'foo' AS bar UNION SELECT 'foo' AS bar

Result:

+-----+
| bar |
+-----+
| foo |
+-----+
1 row in set (0.00 sec)

UNION ALL example:

SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar

Result:

+-----+
| bar |
+-----+
| foo |
| foo |
+-----+
2 rows in set (0.00 sec)

Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.

  • UNION performs a DISTINCT on the result set, eliminating any duplicate rows.

  • UNION ALL does not remove duplicates, and it therefore faster than UNION.

  • Note: While using this commands all selected columns need to be of the same data type.

    Example: If we have two tables, 1) Employee and 2) Customer

  • Employee table data:
  • Customer table data:
  • UNION Example (It removes all duplicate records):
  • 在这里输入图像描述

  • UNION ALL Example (It just concatenate records, not eliminate duplicates, so it is faster than UNION):
  • 在这里输入图像描述


    UNION removes duplicates, whereas UNION ALL does not.

    In order to remove duplicates the result set must be sorted, and this may have an impact on the performance of the UNION, depending on the volume of data being sorted, and the settings of various RDBMS parameters ( For Oracle PGA_AGGREGATE_TARGET with WORKAREA_SIZE_POLICY=AUTO or SORT_AREA_SIZE and SOR_AREA_RETAINED_SIZE if WORKAREA_SIZE_POLICY=MANUAL ).

    Basically, the sort is faster if it can be carried out in memory, but the same caveat about the volume of data applies.

    Of course, if you need data returned without duplicates then you must use UNION, depending on the source of your data.

    I would have commented on the first post to qualify the "is much less performant" comment, but have insufficient reputation (points) to do so.

    链接地址: http://www.djcxy.com/p/41868.html

    上一篇: 在MySql数据库中存储小图片,为什么它与SQL Server不同?

    下一篇: UNION和UNION ALL有什么区别?