SQL执行计划有排序

Par*_*osh 1 sql sql-server sql-execution-plan

我正在使用 AdventureWorks 数据库,运行以下查询:

-- 9
select *
from Production.ProductModel
where not exists
(
    select 1
    from Production.Product
    where Production.Product.ProductModelID = Production.ProductModel.ProductModelID
);
Run Code Online (Sandbox Code Playgroud)

我返回了 9 条记录,这是正确的,但是当我检查执行计划时,我看到已经完成了排序:

在此输入图像描述

在此输入图像描述

为什么要进行排序?它来自内部查询吗?

Stu*_*Stu 5

为什么要进行排序?

SQL Server 决定使用合并联接(计划中的左反半联接)来实现存在检查。

合并连接需要对两个输入进行排序 - 因此它可以执行一次传递并有效地匹配类似排序的输入。

SQL Server 认为为了实现合并联接而对 ProductModelID 进行排序的额外成本与性能优势相比是值得的。

您可以通过查询选项提示强制 SQL Server 使用不同的连接运算符,并检查执行计划以确定优化器是否正确,例如option(loop join);