Skip to main content

The COUNT(X) function only counts non-null values

I was running a tally in a photos table with a text column photos, and I got a surprising result:

sqlite> SELECT media, COUNT(media) FROM photos GROUP BY media;
|0
photo|1813253
video|1131

Why is there a value with 0 results in the tally? That seems odd!

The issue turned out to be a misunderstanding on my part about the COUNT(X) function – it only counts the number of times that X is not NULL.

I had a number of null rows in the database, but they weren’t being counted:

sqlite> SELECT COUNT(*) FROM photos WHERE media IS NULL;
340

The tally query I actually want uses COUNT(*), not COUNT(X):

sqlite> SELECT media, COUNT(*) FROM photos GROUP BY media;
|340
photo|1813253
video|1131

Other thoughts/clues