Learn SQL/Intermediate/NULL Handling/SQL NULL in Aggregate Functions

SQL NULL in Aggregate Functions

COUNT(column), SUM, AVG, MAX, and MIN all silently ignore NULL rows — except COUNT(*), which counts every row regardless.

What & Why

Every standard aggregate function — SUM, AVG, MAX, MIN, and COUNT(column) — simply skips NULL values when computing its result, as if those rows weren't part of the input at all. The one genuine exception is COUNT(*), which counts every row regardless of what any column contains.

See How It Works

BUSINESS QUESTION

Product wants several aggregates computed over the same nullable NPS score column.

iduser_idfeature_idratingnps_scorecommentcreated_at
1101159Clear and useful2024-01-25 12:15:00+00
210224NULLExport worked well2024-02-20 15:40:00+00
3103147Helpful setup flow2024-03-18 09:05:00+00
410433NULLNeeds clearer timing2024-04-08 17:30:00+00
Watch each aggregate handle the same nullable columnStep 1 of 5
COUNT(*)
expressionresult
COUNT(*)4

COUNT(*) counts all four product.feedback rows, including the two rows whose NPS score is NULL.

EXAMPLE QUERY
SELECT
  COUNT(*) AS total_feedback,
  COUNT(nps_score) AS scored_feedback,
  SUM(nps_score) AS score_sum,
  ROUND(AVG(nps_score), 2) AS average_score,
  MAX(nps_score) AS max_score
FROM product.feedback;
Now You Try

Practice this concept

Product wants several aggregates computed over the same nullable NPS score column.

Available schema
product

Prefix tables with product.table_name.

total_feedbackscored_feedbackscore_sumaverage_scoremax_score
product.feedback
ColumnType
idinteger
user_idinteger
feature_idinteger
ratinginteger
nps_scoreinteger
commenttext
created_attimestamp with time zone
moderation_buckettext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario