The difference between UNION and UNION ALL in SQL

Union deletes duplicate items after joining the two tables. bai

Union all joins the two tables without deleting their duplicates.
additional materials:

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

UNION will filter out duplicate records after table linking, so after table linking, the result set will be sorted, duplicate records will be deleted and the result will be returned. In most applications, duplicate records will not be generated. The most common ones are process table and history table UNION. Such as:

select * from users1 union select * from user2

This SQL first fetches the results of the two tables when it runs, then uses the sort space to sort to delete duplicate records, and finally returns the result set. If the amount of table data is large, it may lead to disk sorting.

UNION ALL simply combines the two results and returns. In this way, if there are duplicate data in the two returned result sets, 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 two merged result sets do not contain duplicate data, use UNION ALL, as follows:

select * from user1 union all select * from user2

The following is another example. There are 5 rows of repeated data in tempa and tempa_1, a is from 1-5.

Guess you like

Origin blog.csdn.net/londa/article/details/109442927