SQL Saturday #02

COUNT(primary_key) vs. COUNT(nullable_column) when using GROUP BY


The Question

A catalog manager is auditing their film library ahead of a family-friendly promotion and wants a complete breakdown of how many titles sit in each MPAA rating category (G, PG, PG-13, R, NC-17), including whether any films in the catalog are missing a rating altogether.

The Data:

The Query


Query #1


    SELECT
        f.rating AS Rating,
        COUNT(f.film_id) AS "Rating Count"
    FROM film f
    GROUP BY f.rating;


Query #2


    SELECT
        f.rating AS Rating,
        COUNT(f.rating) AS "Rating Count"
    FROM film f
    GROUP BY f.rating;

The Takeaway

Without NULLs (film table)

In a scenario where there are no NULL values for the MPAA rating category, both queries would return the exact same counts on the film table. Rating counts with no NULL ratings: both queries return the same count for each rating However, under the hood they would behave differently if NULL values existed as we can see below when we introduce NULLs into the table.


With NULLs (sample table, 15 unrated films)

COUNT(film_id) counts every row where film_id (the primary key) is not null. Even if a film had rating = NULL, it would still appear in a NULL bucket with its true row count.

Query #1 results with NULL ratings: COUNT(film_id) shows 15 in the NULL row

COUNT(rating) counts only rows where rating itself is not null. If 15 films were missing a rating, the NULL group would still appear, but its count would show 0 instead of 15.

Query #2 results with NULL ratings: COUNT(rating) shows 0 in the NULL row

That 0 is dangerous. Someone scanning the results will see NULL | 0, and could assume there are no missing ratings, and moves on, so the 15 unrated films slip through unnoticed. With COUNT(film_id), the result shows NULL | 15, which flags the gap right away and points to a follow-up query (WHERE rating IS NULL) to find exactly which titles need attention.

So for this ask, Query #1 is the right choice. When you need to know whether data is missing, count the primary key or use COUNT(*), not the column you're checking.