What is the difference between count(0), count(1).. and count(*) in mySQL/SQL?

后端 未结 9 1860

I was recently asked this question in an interview. I tried this in mySQL, and got the same results(final results). All gave the number of rows in that particular table. Can

相关标签:
9条回答
  • 2020-12-24 02:41
    COUNT(*), COUNT(1) , COUNT(0), COUNT('Y') , ...
    

    All of the above return the total number of records (including the null ones).

    But COUNT('any constant') is faster than COUNT(*).

    0 讨论(0)
  • 2020-12-24 02:44

    Nothing really, unless you specify a field in a table or an expression within parantheses instead of constant values or *

    Let me give you a detailed answer. Count will give you non-null record number of given field. Say you have a table named A

    select 1 from A
    select 0 from A
    select * from A
    

    will all return same number of records, that is the number of rows in table A. Still the output is different. If there are 3 records in table. With X and Y as field names

    select 1 from A will give you
    
    1
    1
    1
    
    select 0 from A will give you
    0
    0
    0
    
    select * from A will give you ( assume two columns X and Y is in the table )
    X      Y
    --     --
    value1 value1
    value2 (null)
    value3 (null)
    

    So, all three queries return the same number. Unless you use

    select count(Y) from A 
    

    since there is only one non-null value you will get 1 as output

    0 讨论(0)
  • 2020-12-24 02:44

    The result will be the same, however COUNT(*) is slower on a lot of production environments today, because in production the db engines can live decades. I prefer to use COUNT(0), someone use COUNT(1), but definitely not COUNT(*) even if its lets say safe to use on modern db engines, I would not depend on the engine, especially if its only one character difference, also the code will be more portable.

    0 讨论(0)
提交回复
热议问题