26

Am I correct in saying:

COUNT(expr)
WHERE expr IS NOT *  

Will count only non nulls?

Will COUNT(*) always count all rows? And What if all columns are null?

iceangel89
  • 6,113
  • 8
  • 40
  • 55

7 Answers7

36

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.

n00dl3
  • 21,213
  • 7
  • 66
  • 76
Godeke
  • 16,131
  • 4
  • 62
  • 86
  • 1
    Is there any way to count nulls too, with COUNT(Expression)? – Jo Smo Apr 04 '14 at 11:02
  • If you do a COUNT( * ) then all rows are counted no matter what the contents of those rows. If you want to see both the total rows *and* the count of rows with values for SomeColumn, do a SELECT COUNT( * ) as AllRows, COUNT(SomeColumn) as SomeColumnCount. AllRows will be the total rows returned by the query, while SomeColumnCount will be the count of rows where SomeColumn had a value. – Godeke Apr 08 '14 at 04:57
21

If you want to count NULLs as well, try

SELECT COUNT(IFNULL(col, 1)) FROM table;
Roey
  • 1,647
  • 21
  • 16
7

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.

Özgür Can Karagöz
  • 1,039
  • 1
  • 13
  • 32
Sergei
  • 2,747
  • 1
  • 17
  • 16
  • "I don't see the point in the record with NULL values". oh it just came to my mind. now when u say this i figured u are right, didnt think abt it when i asked. – iceangel89 Aug 31 '09 at 14:16
3

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

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
2

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;
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
1

If you want to count only the nulls you can also use COUNT() with IF.

Example:

select count(*) as allRows, count(if(nullableField is null, 1, NULL)) as missing from myTable;

You can change the if condiditon to count what you actually want. So you can have multiple counts in one query.

keiki
  • 3,260
  • 3
  • 30
  • 38
0

select count(*) as 'total', sum(if(columna is null, 1, 0)) as 'nulos' from tabla;

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 27 '21 at 13:27