Pathubs SQL Curriculum • Module 10

SQL AVG

Master arithmetic mean aggregation: understand how AVG() calculates totals divided by valid non-NULL counts, explore the critical distinction between NULL and 0, and master AVG(DISTINCT).

⏱️ Estimated Time:45 Minutes
🎯 Level:Beginner
📊 Track:Data Analytics & SQL Mastery
✨ Mode:Interactive Arithmetic Mean & NULL Lab
1

Introduction

An average (or arithmetic mean) is one of the most widely used statistical measures in business, finance, and analytics. It tells you the typical central value of a numeric dataset:

  • Average employee salary: Understanding payroll benchmarks.
  • Average product price: Pricing competitiveness and catalog positioning.
  • Average customer order value: Measuring customer spending health.
  • Average student test marks: Evaluating cohort performance.

In plain language:

Average = Total Sum of Included Values ÷ Quantity of Included Values
2

What Is AVG?

AVG() is a standard SQL aggregate function that computes the arithmetic mean across all numeric inputs in a column or expression:

SELECT AVG(salary)
FROM employees;
3

Basic AVG Syntax

AVG(expression)

The expression is evaluated for each row, and all non-NULL results are summed and divided by the number of non-NULL observations.

4

Your First AVG Query

Consider a small 3-person team with salaries: [40000, 50000, 60000].

SELECT AVG(salary) FROM employees;

Manual Verification: (40,000 + 50,000 + 60,000) ÷ 3 = 150,000 ÷ 3 = 50,000.

Diagram 1: Basic Arithmetic Mean Flow
Values: 40k + 60k + 80k
Sum = 180,000
➔ ÷ 3 values ➔
Average = 60,000
5

AVG With WHERE

When a WHERE filter is present, the database filters candidate rows before computing the mean:

SELECT AVG(salary)
FROM employees
WHERE department = 'Sales';
6

AVG and NULL (Exclusion Rules)

This is one of the most critical concepts in SQL data analytics: AVG() completely ignores NULL input values.

Given 4 records: [40, NULL, 60, 80]:

  1. The numerator (Sum) adds only non-NULL numbers: 40 + 60 + 80 = 180.
  2. The denominator (Count) counts only non-NULL entries: 3 items.
  3. The calculation is: 180 ÷ 3 = 60 (NOT 180 ÷ 4).
Diagram 2: NULL Excluded from Numerator & Denominator
Values: 40, NULL, 60, 80
Discard NULL ➔ [40, 60, 80]
➔ 180 ÷ 3 ➔
AVG = 60
7

AVG vs Zero (Crucial Difference)

NULL means missing or unknown, whereas 0 is a known numeric measurement:

With NULL: [40, NULL, 60, 80]
AVG = 60

(40 + 60 + 80) ÷ 3 = 180 ÷ 3 = 60

With Zero: [40, 0, 60, 80]
AVG = 45

(40 + 0 + 60 + 80) ÷ 4 = 180 ÷ 4 = 45

Diagram 3: Side-by-Side Impact of NULL vs 0
[40, NULL, 60, 80]
Count = 3 ➔ AVG = 60
vs
[40, 0, 60, 80]
Count = 4 ➔ AVG = 45
8

AVG With No Non-NULL Values

What happens when AVG() is run on an empty set or on rows where every value is NULL?

ℹ️
Standard SQL Definition: PostgreSQL and MySQL explicitly document that AVG() returns NULL when there are zero non-NULL rows. It does not return 0.
9

AVG With Calculated Expressions

You can aggregate arithmetic expressions directly:

SELECT AVG(price * quantity) AS avg_line_item_value
FROM order_items;
10

AVG(DISTINCT ...) Patterns

Adding DISTINCT inside AVG() eliminates duplicate values before calculating the arithmetic mean:

SELECT AVG(DISTINCT rating)
FROM reviews;

Given ratings [5, 5, 5, 1]: standard AVG is (16 ÷ 4) = 4.0. However, AVG(DISTINCT) averages unique ratings [5, 1] giving (6 ÷ 2) = 3.0.

11

AVG vs SUM and COUNT

The mathematical triad of SQL aggregates:

FunctionFormula / ActionExample with [40, NULL, 60]
SUM(col)Adds numeric values40 + 60 = 100
COUNT(col)Counts non-NULL observations2 observations
AVG(col)SUM(col) ÷ COUNT(col)100 ÷ 2 = 50
12

Understanding AVG Results

The calculated mean does not have to be one of the values present in the table. For example, the average of [10, 20] is 15 (even though neither row has the value 15).

Live Interactive AVG Lab
📦 Employees & Salaries
#NameDeptSalaryAVG Inclusion Status
1Aarav PatelEngineering₹75,000₹75,000 added to sum & count
2Diya SharmaSalesNULLSalary is NULL (Ignored in sum & count)
3Ishaan VermaEngineering₹60,000₹60,000 added to sum & count
4Riya GuptaSales₹45,000₹45,000 added to sum & count
5Kabir SinghMarketing₹50,000₹50,000 added to sum & count
6Ananya RoySales₹45,000₹45,000 added to sum & count
7Rohan MehtaMarketingNULLSalary is NULL (Ignored in sum & count)
8Tara NairEngineering₹90,000₹90,000 added to sum & count
✍️ SQL Aggregate Query● Scalar Output
SELECT AVG(salary) AS avg_company_salary
FROM employees;
₹60,833.33
Output column: avg_company_salary
Calculation: (₹75,000 + ₹60,000 + ₹45,000 + ₹50,000 + ₹45,000 + ₹90,000) ÷ 6 = ₹60,833.33
13

Common AVG Mistakes

1. Treating NULL as Zero

Remember that NULL values do not reduce the average; they are completely omitted from both the numerator and denominator.

2. Expecting 0 for Empty Match Sets

If 0 rows match your WHERE filter, AVG() returns NULL, not 0.

3. Confusing AVG with SUM or COUNT

SUM gives the grand total, COUNT gives the number of items, and AVG divides SUM by COUNT.

🧠 Interactive Challenge: Predict The Result (1 of 3)
SELECT AVG(score) FROM exam_results;
With scores [20, 40, NULL, 60], what will AVG(score) return?
14

Practical Step-by-Step Exercises

Task GoalTarget TableRequired SQL SolutionPattern Used
1. Average Employee SalaryemployeesSELECT AVG(salary) FROM employees;Basic column AVG
2. Average Product PriceproductsSELECT AVG(price) FROM products;Catalog pricing mean
3. Average Sales for ElectronicssalesSELECT AVG(amount) FROM sales WHERE category = 'Electronics';WHERE + AVG
4. Average Line-Item Valueorder_itemsSELECT AVG(price * quantity) FROM order_items;Expression average
5. Average Distinct RatingreviewsSELECT AVG(DISTINCT rating) FROM reviews;Deduplicated distinct mean
15

AVG Best Practices

  • Always Alias Output: Write AVG(salary) AS average_salary for clarity.
  • Be Aware of NULL Impact: Recognize that omitting missing values changes both the total sum and the dividing count.
  • Use WHERE for Specific Cohorts: Filter by date, status, or category prior to aggregation.
  • Format Decimals in Presentation Layer: Databases return floating precision; format decimals cleanly in UI components.
16

What You Should Know Now

  • AVG(col): Calculates arithmetic mean
  • AVG(expr): Averages computed expressions (e.g. price * qty)
  • NULL Exclusion: NULL rows are ignored in sum and count
  • NULL vs Zero: 0 decreases the mean; NULL is skipped
  • Empty Sets: Returns NULL when 0 valid rows match
  • AVG(DISTINCT): Averages unique values only

🎯 Knowledge Check Quiz: SQL AVG

Test your understanding of arithmetic means, NULL handling, zero vs NULL impact, and distinct averages.

1. What does the SQL AVG aggregate function compute?
2. How does AVG handle NULL values in a column?
3. Why is replacing NULL with 0 in an average calculation potentially misleading?
4. If all candidate rows in a table contain NULL for the target column, what does SELECT AVG(column) return?
5. How is AVG related to the SUM and COUNT aggregate functions?
6. Does the result of an AVG() query always have to match one of the existing values in the table?
7. Which query correctly calculates the average total order cost from order_items with price and quantity columns?
8. Given salaries [50000, 50000, 100000], what is the difference between AVG(salary) and AVG(DISTINCT salary)?