使用 table 的 1000 万行提高简单查询的性能

Improve performance on simple query with table of 10 million rows

考虑有一个很大的 table 叫做.... BigTable 有 1000 万行。原来没有主键,所以我添加了标识列以及主键约束和聚簇索引。

ALTER TABLE BigTable ADD id int identity(1,1) not null;
ALTER TABLE BigTable ADD CONSTRAINT pk_id primary key CLUSTERED (id);

然后我做了一个简单的select

select id from BigTable;

SQL 服务器取得了 1 mins 23 seconds return 结果。

set statistics time on
 SQL Server Execution Times:
 CPU time = 10063 ms,  elapsed time = 65740 ms.

execution plan just simply showed a "Clustered Index scan" with cost of 100%
Number of Rows Read      10332000
Estimated Operator Cost  1740.89(100%)
Estimated I/O Cost       1729.52
Estimated Cpu Cost       11.3654
Estimated SubTree Cost   1740.89
Number of Executions     1

我之所以使用这个简单的查询是因为我真的试图从查询中排除性能因素,然后仍然试图弄清楚:如何让这个简单的查询return结果小于几秒钟?这真的是我可以从 SQL 服务器获得的最大性能来查询 1000 万行吗?

要扫描聚集索引中 任何 列的所有值,需要完整的 table 扫描。如果您想优化检索所有 id 或计算行数,请尝试 id 上的非聚集索引或列存储索引。