zoukankan      html  css  js  c++  java
  • Difference between count(1) and count(*)

    Some people prefer count(1) over count(*) and using count(1) to optimize his statements, but actually they have not difference.

    Here is test code and data(using the TRAN for execute more speed only):

    BEGIN TRAN
    CREATE
    TABLE TestCount(C1 VARCHAR(400),C2 VARCHAR(300),C3 VARCHAR(150) NOT NULL,C4 VARCHAR(80),C5 VARCHAR(38) NOT NULL,C6 INT) DECLARE @COUNT INT =1 SET NOCOUNT ON WHILE @COUNT<=1500000 BEGIN INSERT TestCount SELECT NEWID(),NEWID(),NEWID(),NEWID(),NEWID(),@COUNT SET @COUNT=@COUNT+1 END
    commit

    As to count(1),count(*),count('anything'), they are the same about results and execultion plan(it used "table scan", because the table is heap)

    As to count(column)

    It noly count the rows of is not null for the columns:

    UPDATE TOP (1) TestCount SET c1 =NULL 

    How to execute count(*) of execution engine

    Execution engine will use a have index's column to count count(*)(if the table have index), of cause, for performance reasons, engine will prefer the narrowest index.

    CREATE NONCLUSTERED INDEX IDX_C5 ON TestCount(C5)

    add a index in C6(the column type is int, is 4 bytes)

    CREATE NONCLUSTERED INDEX IDX_C6 ON TestCount(C6)

    Engine used more  narrow index to count.

     comparison of count(wide index column), count(narrow index column) and count(no index column)

    CREATE NONCLUSTERED INDEX IDX_C2 ON TestCount(C2)

    So, count(no index column) performance is poor and index the more narrow the better, the performance more batter too.

    Now,  we will compare more detail between count(1) and count(*), we already know their "query cost" is same and the table has 3 index: C2/C5/C6

     Scan page is same and  IO cast is same too

    SET STATISTICS IO ON
    SET STATISTICS TIME ON
    SELECT COUNT(1) FROM TestCount    
    SET STATISTICS IO OFF
    SET STATISTICS TIME OFF
    ------------------------
    PRINT 'NEXT plan'
    ------------------------
    SET STATISTICS IO ON
    SET STATISTICS TIME ON
    SELECT COUNT(*) FROM TestCount    
    SET STATISTICS IO OFF
    SET STATISTICS TIME OFF

  • 相关阅读:
    POJ 2485 Highways &amp;&amp; HDU1102(20/200)
    easyui 后台框架搭建
    启动第二个Activity
    Apache配置基于域名的虚拟主机
    POJ_1679_The Unique MST(次小生成树模板)
    MySQL学习笔记
    数据库学习之简单的SQL语句
    HDU-4643-GSM(DFS)
    Android Studio VS Eclipse (还在用Eclipse?你OUT了!)
    使用国内镜像源来加速python pypi包的安装
  • 原文地址:https://www.cnblogs.com/ziqiumeng/p/10129487.html
Copyright © 2011-2022 走看看