0
Why COUNT() doesn’t count NULL values in MySQL?
Hey everyone 👋 I’m learning SQL and got a small doubt. COUNT() counts rows, but it skips NULL values. Why does COUNT() ignore NULL? And also, how does COUNT(IF(...)) work when there are NULLs? Here’s a small example 👇 CREATE TABLE students ( id INT, marks INT ); INSERT INTO students VALUES (1, 90), (2, NULL), (3, 80); SELECT COUNT(marks) AS count_marks, COUNT(*) AS count_rows FROM students; Output: count_marks → 2 count_rows → 3 Can someone explain why COUNT(marks) = 2 instead of 3?
1 ответ
+ 3
COUNT() ignores NULL because NULL means “no value.” COUNT(marks) counts only rows where marks is not NULL, while COUNT(*) counts all rows.
So in your example, marks has 2 real values and 1 NULL → result is 2 vs 3.
Solution:
If you want to treat NULL as 0 or count them too, use: COUNT(IFNULL(marks, 0))
or simply use: COUNT(*) -- counts all rows including NULLs
Good luck!