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

后端 未结 13 2056
醉梦人生
醉梦人生 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:03

    There is an article showing that the COUNT(1) on Oracle is just an alias to COUNT(*), with a proof about that.

    I will quote some parts:

    There is a part of the database software that is called “The Optimizer”, which is defined in the official documentation as “Built-in database software that determines the most efficient way to execute a SQL statement“.

    One of the components of the optimizer is called “the transformer”, whose role is to determine whether it is advantageous to rewrite the original SQL statement into a semantically equivalent SQL statement that could be more efficient.

    Would you like to see what the optimizer does when you write a query using COUNT(1)?

    With a user with ALTER SESSION privilege, you can put a tracefile_identifier, enable the optimizer tracing and run the COUNT(1) select, like: SELECT /* test-1 */ COUNT(1) FROM employees;.

    After that, you need to localize the trace files, what can be done with SELECT VALUE FROM V$DIAG_INFO WHERE NAME = 'Diag Trace';. Later on the file, you will find:

    SELECT COUNT(*) “COUNT(1)” FROM “COURSE”.”EMPLOYEES” “EMPLOYEES”
    

    As you can see, it's just an alias for COUNT(*).

    Another important comment: the COUNT(*) was really faster two decades ago on Oracle, before Oracle 7.3:

    Count(1) has been rewritten in count(*) since 7.3 because Oracle like to Auto-tune mythic statements. In earlier Oracle7, oracle had to evaluate (1) for each row, as a function, before DETERMINISTIC and NON-DETERMINISTIC exist.

    So two decades ago, count(*) was faster

    For another databases as Sql Server, it should be researched individually for each one.

    I know that this question is specific for Sql Server, but the other questions on SO about the same subject, without mention the database, was closed and marked as duplicated from this answer.

提交回复
热议问题