Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL COUNT() and nulls

Tags:

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?

like image 589
iceangel89 Avatar asked Aug 30 '09 15:08

iceangel89


People also ask

Does COUNT COUNT NULL in MySQL?

The MySQL COUNT() function provides a number of records in the result set from a table when an SQL SELECT statement is executed. This function does not count the NULL values.

Does COUNT () ignores NULL?

COUNT(expression) does not count NULL values.

Does COUNT work on NULL?

How to Count SQL NULL values in a column? The COUNT() function is used to obtain the total number of the rows in the result set. When we use this function with the star sign it count all rows from the table regardless of NULL values.

How do I COUNT NULL rows in MySQL?

SELECT COUNT(IF(average IS NULL,1,0)) FROM table; It worked like a charm for me! This answer is very useful and help full.


1 Answers

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.

like image 86
Godeke Avatar answered Sep 21 '22 18:09

Godeke