Count(*) vs Count(1) - SQL Server

后端 未结 13 2458
醉梦人生
醉梦人生 2020-11-21 05:21

Just wondering if any of you people use Count(1) over Count(*) and if there is a noticeable difference in performance or if this is just a legacy h

13条回答
  •  庸人自扰
    2020-11-21 06:13

    In the SQL-92 Standard, COUNT(*) specifically means "the cardinality of the table expression" (could be a base table, `VIEW, derived table, CTE, etc).

    I guess the idea was that COUNT(*) is easy to parse. Using any other expression requires the parser to ensure it doesn't reference any columns (COUNT('a') where a is a literal and COUNT(a) where a is a column can yield different results).

    In the same vein, COUNT(*) can be easily picked out by a human coder familiar with the SQL Standards, a useful skill when working with more than one vendor's SQL offering.

    Also, in the special case SELECT COUNT(*) FROM MyPersistedTable;, the thinking is the DBMS is likely to hold statistics for the cardinality of the table.

    Therefore, because COUNT(1) and COUNT(*) are semantically equivalent, I use COUNT(*).

提交回复
热议问题