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

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

    I ran a quick test on SQL Server 2012 on an 8 GB RAM hyper-v box. You can see the results for yourself. I was not running any other windowed application apart from SQL Server Management Studio while running these tests.

    My table schema:

    CREATE TABLE [dbo].[employee](
        [Id] [bigint] IDENTITY(1,1) NOT NULL,
        [Name] [nvarchar](50) NOT NULL,
     CONSTRAINT [PK_employee] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    

    Total number of records in Employee table: 178090131 (~ 178 million rows)

    First Query:

    Set Statistics Time On
    Go    
    Select Count(*) From Employee
    Go    
    Set Statistics Time Off
    Go
    

    Result of First Query:

     SQL Server parse and compile time: 
     CPU time = 0 ms, elapsed time = 35 ms.
    
     (1 row(s) affected)
    
     SQL Server Execution Times:
       CPU time = 10766 ms,  elapsed time = 70265 ms.
     SQL Server parse and compile time: 
       CPU time = 0 ms, elapsed time = 0 ms.
    

    Second Query:

        Set Statistics Time On
        Go    
        Select Count(1) From Employee
        Go    
        Set Statistics Time Off
        Go
    

    Result of Second Query:

     SQL Server parse and compile time: 
       CPU time = 14 ms, elapsed time = 14 ms.
    
    (1 row(s) affected)
    
     SQL Server Execution Times:
       CPU time = 11031 ms,  elapsed time = 70182 ms.
     SQL Server parse and compile time: 
       CPU time = 0 ms, elapsed time = 0 ms.
    

    You can notice there is a difference of 83 (= 70265 - 70182) milliseconds which can easily be attributed to exact system condition at the time queries are run. Also I did a single run, so this difference will become more accurate if I do several runs and do some averaging. If for such a huge data-set the difference is coming less than 100 milliseconds, then we can easily conclude that the two queries do not have any performance difference exhibited by the SQL Server Engine.

    Note : RAM hits close to 100% usage in both the runs. I restarted SQL Server service before starting both the runs.

提交回复
热议问题