Video in progress

How do aggregate functions like `SUM` and `AVG` treat NULL values?

Aggregates simply skip NULL values. So AVG is computed only over the non-NULL ones, and if there are no rows at all, or all of them are NULL, SUM returns NULL, not 0.

📖 Answer

The ratings table has these score values: 5, 3, NULL, 4.

SELECT sum(score),       -- 12
       avg(score),       -- 4.0  (12 / 3, the NULL wasn't counted)
       count(score),     -- 3
       count(*)          -- 4
FROM ratings;

If NULL means "a score of 0", you need to write avg(coalesce(score, 0)), and the result becomes 3.0. Which meaning is right depends on the business, so that's your call.

A common mistake in Java:

@Query("select sum(o.total) from Order o where o.userId = :id")
BigDecimal totalSpent(Long id);   // returns null when there are no orders!

Then totalSpent(id).compareTo(...) throws an NPE. The fix is coalesce(sum(o.total), 0) in SQL, or a null check in Java.