Learn SQL/Beginner/Aggregate Functions/SQL Aggregates and NULL

SQL Aggregates and NULL

Every aggregate function silently ignores NULLs — except COUNT(*), which is the one exception.

What & Why

SUM, AVG, MIN, and MAX all skip NULL values as if those rows didn't exist for that column. COUNT(*) is the one exception — it counts every row regardless of NULLs anywhere in it.

See How It Works

BUSINESS QUESTION

Watch how AVG(nps_score) handles product feedback rows where the score is NULL.

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 the aggregate accumulateRow 1 of 4
AVG(nps_score)
rowfeedbackcolumnnps_scorestatusrunning avg
1Feedback #1nps_score9ADD9
2Feedback #2nps_scoreNULLWAIT
3Feedback #3nps_score7WAIT
4Feedback #4nps_scoreNULLWAIT
Running resultAVG(nps_score) = 9

9 is added; the running average becomes 9.

EXAMPLE QUERY
SELECT AVG(nps_score) AS avg_nps_score
FROM product.feedback;
Now You Try

Practice this concept

Marketing wants to compare all leads with leads that have qualification and conversion timestamps.

Available schema
marketing

Prefix tables with marketing.table_name.

total_leadsqualified_leadsconverted_leads
marketing.leads
ColumnType
idinteger
campaign_idinteger
emailtext
created_attimestamp with time zone
qualified_attimestamp with time zone
converted_attimestamp with time zone
lead_scoreinteger
sourcetext
countrytext
archive_statustext
query.sql
Beginner business practice

Sign up free to try it on a real business scenario