The difference between SQL Union efficiency and UNION ALL

Source: Internet
Author: User

To merge records from multiple tables and sort them as follows:

SELECT * FROM (SELECT * FROM Table A

Union
SELECT * FROM Table B

Union
SELECT * Table C) as H order by H. Desc

In the database tutorial, the Union and UNION ALL keywords combine two result sets into one, but both are different in terms of usage and efficiency.

The Union filters out duplicate records after a table link, so the resulting result sets are sorted after the table is connected, the duplicate records are deleted, and the results are returned.

Such as:

SELECT * FROM Test_union1
Union
SELECT * FROM Test_union2


This SQL is run with the result of two tables first, then sorted by sorting to delete duplicate records, and finally return the result set, if the table data volume may cause the disk to sort.
The Union all simply merges the two results and returns. Thus, if the returned two result sets have duplicate data, the returned result set will contain duplicate data.
In terms of efficiency, union All is much faster than union, so if you can confirm that the merged two result sets do not contain duplicate data, then use UNION ALL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.