sql-server - 使用 'where then Union' 或使用 'Union then Where'

标签 sql-server performance union rdbms query-performance

请记住以下两种类型的查询:

--query1
Select someFields
From someTables
Where someWhereClues
Union all
Select someFields
FROM some Tables
Where someWhereClues

--query2
Select * FROM (
    Select someFields 
    From someTables
    Union all 
    Select someFields
    FROM someTables
    ) DT
Where someMixedWhereClues

Note :
In both queries final result fields are same

我以为是第一个。查询速度更快或者性能更好!
但经过一些研究后,我对此感到困惑note :

SQL Server (as a sample of RDBMS) first reads whole data then seek records. => so in both queries all records will read and seek.

请帮助我解决我的误解,以及 query1 和 query2 之间是否还有其他差异?

<小时/>

编辑:添加示例计划:

select t.Name, t.type from sys.tables t where t.type = 'U'
union all
select t.Name, t.type from sys.objects t where t.type = 'U'

select * from (
    select t.Name, t.type from sys.tables t
    union all
    select t.Name, t.type from sys.objects t
    ) dt
where dt.type = 'U'

执行计划是: enter image description here enter image description here

both are same and 50%

最佳答案

SQL Server query optimizer ,优化两个查询,使您获得几乎相同的性能。

关于sql-server - 使用 'where then Union' 或使用 'Union then Where',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29099113/

相关文章:

sql-server - 按键值顺序排序

sql-server - 在一行中创建并传递表值参数

c++ - std::push_back 使用起来相对昂贵吗?

garbage-collection - 在 Julia 中高效优雅地迭代集合和数字的并集

sql - 从多个表中获取数据

java - Quartz 调度程序不在 dropwizard 应用程序中执行 SQL 查询

c# - 我什么时候应该读一个文件,什么时候应该逐行阅读?

sql-server - SQL Server 体系结构指南

sql - 使用联合按子类别排序

mysql - 从两个表中选择第一行