performance of union versus union all

2020-02-11 17:51发布

I have to run a select statement across several tables. I am sure the tables return different records. I am anyway using UNION ALL.

Is it better to use UNION or of UNION ALL in performance terms when I am sure the tables return different records?

5条回答
冷血范
2楼-- · 2020-02-11 18:25

UNION ALL always is faster, because UNION exclude duplicated entries

查看更多
不美不萌又怎样
3楼-- · 2020-02-11 18:31

It is better to use UNION ALL when you know you want all the result rows, whether or not you know they'll be distinct or not. UNION without "all" will always perform the "distinct check", regardless of what the data actually is.

查看更多
淡お忘
4楼-- · 2020-02-11 18:34

Why is UNION ALL faster? Because UNION must do a sort to remove the duplicates. If you do not need to remove duplicates then UNION ALL is the better option, however UNION does have a purpose and should be used when appropriate.

查看更多
祖国的老花朵
5楼-- · 2020-02-11 18:40

UNION implement internally two queries. 1.SELECT which will return a dataset 2.DISTINCT. Anyone who has studied database internals can easily understand that a DISTINCT clause is extremely costly in terms of processing.

If you are pretty sure that the resultant dataset need not have unique rows then we can skip UNION and use UNION ALL instead.

UNION ALL will be same as UNION except that it doesn't fire a DISTINCT internally sparing us costly operations

查看更多
趁早两清
6楼-- · 2020-02-11 18:41

UNION ALL will perform better than UNION when you're not concerned about eliminating duplicate records because you're avoiding an expensive distinct sort operation. See: SQL SERVER – Difference Between Union vs. Union All – Optimal Performance Comparison

查看更多
登录 后发表回答