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

后端 未结 13 2053
醉梦人生
醉梦人生 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 05:57

    As this question comes up again and again, here is one more answer. I hope to add something for beginners wondering about "best practice" here.

    SELECT COUNT(*) FROM something counts records which is an easy task.

    SELECT COUNT(1) FROM something retrieves a 1 per record and than counts the 1s that are not null, which is essentially counting records, only more complicated.

    Having said this: Good dbms notice that the second statement will result in the same count as the first statement and re-interprete it accordingly, as not to do unnecessary work. So usually both statements will result in the same execution plan and take the same amount of time.

    However from the point of readability you should use the first statement. You want to count records, so count records, not expressions. Use COUNT(expression) only when you want to count non-null occurences of something.

提交回复
热议问题