0

I have a table MY_TABLE with approximately 9 million rows.

There are in total of 38 columns in this table. The columns that are relevant to my question are:

  • RECORD_ID: identity, bigint, with unique clustered index
  • RECORD_CREATED: datetime, with non-unique & non-clustered index

Now I run the following two queries and naturally expect the first one to execute faster because the data is being sorted by a column that has a unique clustered index but somehow it executes 271 times(!) slower.

SELECT TOP 1 
    RECORD_ID 
FROM 
    MY_TABLE 
WHERE 
    RECORD_CREATED >= '20140801' 
ORDER BY 
    RECORD_ID

SELECT TOP 1 
    RECORD_ID 
FROM 
    MY_TABLE 
WHERE 
    RECORD_CREATED >= '20140801' 
ORDER BY 
    RECORD_CREATED

The execution times are 1630 ms and 6 ms, respectively.

Please advise.

P.S.: Due to security policies of the environment I cannot see the execution plan or use SQL Profiler.

4

1 回答 1

2

SQL Server 对如何执行此查询有几个选择。它可以首先对所有项目进行排序,利用您提到的索引,然后通过过滤掉与 WHERE 子句不匹配的任何项目来跟进。但是,减少您首先使用的数据集的大小通常会更快,因此您不必对尽可能多的项目进行排序。

所以 SQL Server 最有可能选择首先执行WHERE过滤器。当它这样做时,它很可能首先使用 RECORD_CREATED 上的非唯一、非聚集索引来跳过 RECORD_CREATED 小于“20140801”的所有项目,然后获取之后的所有项目。

此时,所有项目都按照它们在 RECORD_CREATED 索引中的顺序进行了预排序,因此第二个查询不需要额外的工作,但第一个查询必须对已选择的记录执行排序.

于 2014-09-10T18:31:24.430 回答