选择计数(ID)和选择计数(*)之间的性能差异

时间:2016-08-17 20:36:28

标签: sql performance tsql select count

下面有两个查询,其中ID列的返回计数不包括NULL值 第二个查询将返回表中包含NULL行的所有行的计数。

select COUNT(ID) from TableName  

select COUNT(*) from TableName

我的困惑: 有没有性能差异?

1 个答案:

答案 0 :(得分:1)

  

TL / DR:计划可能不一样,你应该在适当的时候进行测试   数据并确保您拥有正确的索引,然后根据您的调查选择最佳解决方案。

查询计划可能不一样,具体取决于COUNT函数中使用的列的索引和可为空性。

在下面的示例中,我创建了一个表并用一百万行填充它。 除了列' b'。

之外,所有列都已编入索引

结论是,其中一些查询确实产生了相同的执行计划,但大多数查询都不同。

这是在SQL Server 2014上测试的,此时我无法访问2012的实例。您应该自己测试一下以找出最佳解决方案。

create table t1(id bigint identity, 
                dt datetime2(7) not null default(sysdatetime()), 
                a char(800) null, 
                b char(800) null,
                c char(800) null);

-- We will use these 4 indexes. Only column 'b' does not have any supporting index on it.
alter table t1 add constraint [pk_t1]  primary key NONCLUSTERED (id);
create clustered index cix_dt on t1(dt);
create nonclustered index ix_a on t1(a);
create nonclustered index ix_c on t1(c);

insert into T1 (a, b, c) 
select top 1000000 
    a = case when low = 1 then null else left(REPLICATE(newid(), low), 800) end, 
    b = case when low between 1 and 10 then null else left(REPLICATE(newid(), 800-low), 800) end,
    c = case when low between 1 and 192 then null else left(REPLICATE(newid(), 800-low), 800) end
from master..spt_values 
cross join (select 1 from master..spt_values) m(ock)
where type = 'p';


checkpoint;

-- All rows, no matter if any columns are null or not
-- Uses primary key index
select count(*) from t1;

-- All not null, 
-- Uses primary key index
select count(id) from t1;

-- Some values of 'a' are null
-- Uses the index on 'a'
select count(a) from t1;

-- Some values of b are null
-- Uses the clustered index
select count(b) from t1;

-- No values of dt are null and the table have a clustered index on 'dt'
-- Uses primary key index and not the clustered index as one could expect.
select count(dt) from t1;

-- Most values of c are null
-- Uses the index on c
select count(c) from t1;

Different select count results

如果我们更明确地想要我们的计划,会发生什么?如果我们告诉查询规划器我们只想获得没有null的行,那会改变什么吗?

-- Homework!
-- What happens if we explicitly count only rows where the column is not null? What if we add a filtered index to support this query?
-- Hint: It will once again be different than the other queries.
create index ix_c2 on t1(c) where c is not null;
select count(*) from t1 where c is not null;
相关问题