Sub topic 8
Aggregates and NULL: COUNT(*) vs COUNT(column), SUM, AVG
Prerequisites and the main rule
This chapter assumes you know basic SELECT, WHERE, and GROUP BY queries. You should also be familiar with tables, rows, and columns.
An aggregate function combines values from several rows into one result. NULL means that a value is missing, unknown, or not applicable. Most aggregate functions ignore NULL values. COUNT(*) is the important exception because it counts rows, not values.
Use this sample table:
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INTEGER,
commission NUMERIC(8,2)
);
INSERT INTO employees (id, name, manager_id, commission) VALUES
(1, 'Ada', NULL, NULL),
(2, 'Ben', 1, 100.00),
(3, 'Cy', 1, NULL),
(4, 'Di', 2, 300.00);Comparing the counting functions
The following query counts all rows and then counts only rows with a known commission:
SELECT COUNT(*) AS all_rows,
COUNT(commission) AS rows_with_commission
FROM employees;The result is:
| all_rows | rows_with_commission |
|---|---|
| 4 | 2 |
COUNT(*) counts all four rows, including Ada and Cy. COUNT(commission) counts only Ben and Di because their commission is not NULL.
This distinction is useful when checking data completeness. The difference between the two counts tells you how many rows have no commission value.
SUM and AVG ignore NULL
SUM(commission) adds the known commissions. It does not treat missing commissions as zero:
SELECT SUM(commission) AS total_commission,
AVG(commission) AS average_known_commission
FROM employees;The result is:
| total_commission | average_known_commission |
|---|---|
| 400.00 | 200.00 |
The sum is 100 plus 300. The average is 400 divided by 2, the number of known commissions. It is not divided by all four employees.
If you deliberately want missing commissions to count as zero, replace NULL before calculating:
SELECT AVG(COALESCE(commission, 0)) AS average_with_missing_as_zero
FROM employees;The result is 100.00 because 400 is divided by 4.
Empty input and grouped results
SUM and AVG return NULL when they have no known input values. COUNT returns zero. You can use COALESCE when a report needs a numeric zero instead:
SELECT COALESCE(SUM(commission), 0) AS total_commission
FROM employees
WHERE manager_id = 99;With GROUP BY, each group applies the same rules independently. A group can contain rows but still have a NULL sum or average if every value in that group is NULL.
Exercise
In the employees table, what do COUNT(*), COUNT(commission), SUM(commission), and AVG(commission) return?
Show answer
They return 4, 2, 400.00, and 200.00. COUNT(*) counts rows; the other three calculations use only the two non-NULL commission values.