MySQL COUNT() and nulls

后端 未结 5 978
庸人自扰
庸人自扰 2020-12-09 10:05

Am I correct in saying:

COUNT(expr)
WHERE expr IS NOT *  

Will count only non nulls?

Will COUN

相关标签:
5条回答
  • 2020-12-09 10:28

    If you want to count NULLs as well, try

    SELECT COUNT(IFNULL(col, 1)) FROM table;
    
    0 讨论(0)
  • 2020-12-09 10:32

    just checked:

    select count(*)
    

    returns 1 with one record filled with NULLs

    select count(field)
    

    returns 0.

    I don't see the point in the record with NULL values. Such record must not exist.

    0 讨论(0)
  • 2020-12-09 10:34

    Correct. COUNT(*) is all rows in the table, COUNT(Expression) is where the expression is non-null only.

    If all columns are NULL (which indicates you don't have a primary key, so this shouldn't happen in a normalized database) COUNT(*) still returns all of the rows inserted. Just don't do that.

    You can think of the * symbol as meaning "in the table" and not "in any column".

    This is covered in the MySQL Reference Manual.

    0 讨论(0)
  • 2020-12-09 10:35

    Using MySQL I found this simple way:

    SELECT count(ifnull(col,1)) FROM table WHERE col IS NULL;
    

    This way will not work:

    SELECT count(col) FROM table WHERE col IS NULL;
    
    0 讨论(0)
  • 2020-12-09 10:49

    count(*) is not for non-null columns, it's just the way to ask to count all rows. Roughly equivalent to count(1).

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