我有以下疑问:

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值和列中空值的计数。


当前回答

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

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

其他回答

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

最好使用

Count(1) in place of column name or * 

要计算表中的行数,它比任何格式都要快,因为它从不检查表中的列名是否存在

如果您的表中有一个列是固定的,如果您想使用多个列,那么您必须指定需要计算多少列......

谢谢,

我们可以使用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(*)是通过查看相关表上的索引来计算的,而不是实际的数据行。由于没有指定特定的列,因此不需要考虑实际的行及其值(如果计算特定的列,就会遇到这种情况)。允许数据库使用索引数据比让它计算“真实的”行要快得多。