我有以下疑问:

select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;

如果我将所有对count(column_name)的调用替换为count(*),会有什么不同?

这个问题的灵感来自于如何在Oracle中查找表中的重复值。


为了澄清接受的答案(可能是我的问题),将count(column_name)替换为count(*)将在结果中返回一个额外的行,其中包含null值和列中空值的计数。


当前回答

我们可以使用Stack Exchange Data Explorer通过一个简单的查询来说明两者的区别。Stack Overflow数据库中的Users表的列通常为空,就像用户的Website URL一样。

-- count(column_name) vs. count(*)
-- Illustrates the difference between counting a column
-- that can hold null values, a  'not null' column, and  count(*)

select count(WebsiteUrl), count(Id), count(*) from Users

如果您在Data Explorer中运行上述查询,您将看到count(Id)和count(*)的计数是相同的,因为Id列不允许空值。但是,WebsiteUrl计数要低得多,因为该列允许为空。

其他回答

COUNT(*)语句指示SQL Server返回表中的所有行,包括null。 COUNT(column_name)只检索行上具有非空值的行。

请参阅SQL Server 2008的测试执行代码:

-- Variable table
DECLARE @Table TABLE
(
      CustomerId int NULL 
    , Name nvarchar(50) NULL
)

-- Insert some records for tests
INSERT INTO @Table VALUES( NULL, 'Pedro')
INSERT INTO @Table VALUES( 1, 'Juan')
INSERT INTO @Table VALUES( 2, 'Pablo')
INSERT INTO @Table VALUES( 3, 'Marcelo')
INSERT INTO @Table VALUES( NULL, 'Leonardo')
INSERT INTO @Table VALUES( 4, 'Ignacio')

-- Get all the collumns by indicating *
SELECT  COUNT(*) AS 'AllRowsCount'
FROM    @Table

-- Get only content columns ( exluce NULLs )
SELECT  COUNT(CustomerId) AS 'OnlyNotNullCounts'
FROM    @Table

使用*和特定列之间的另一个微小区别是,在列的情况下,你可以添加关键字DISTINCT,并将计数限制为不同的值:

select column_a, count(distinct column_b)
from table
group by column_a
having count(distinct column_b) > 1;

另一个细微的区别是,在某些数据库实现中,count(*)是通过查看相关表上的索引来计算的,而不是实际的数据行。由于没有指定特定的列,因此不需要考虑实际的行及其值(如果计算特定的列,就会遇到这种情况)。允许数据库使用索引数据比让它计算“真实的”行要快得多。

文档中的解释有助于解释这一点:

COUNT(*)返回组中的项数,包括NULL值和重复项。 COUNT(表达式)计算组中每一行的表达式,并返回非空值的数目。

所以count(*)包含空值,其他方法不包含。

我们可以使用Stack Exchange Data Explorer通过一个简单的查询来说明两者的区别。Stack Overflow数据库中的Users表的列通常为空,就像用户的Website URL一样。

-- count(column_name) vs. count(*)
-- Illustrates the difference between counting a column
-- that can hold null values, a  'not null' column, and  count(*)

select count(WebsiteUrl), count(Id), count(*) from Users

如果您在Data Explorer中运行上述查询,您将看到count(Id)和count(*)的计数是相同的,因为Id列不允许空值。但是,WebsiteUrl计数要低得多,因为该列允许为空。