What do the five basic aggregate functions do, and what do they return when there are no rows?
COUNT counts rows or non-NULL values. SUM adds up a numeric column. AVG divides the sum by the number of non-NULL values. MIN and MAX return the smallest and largest value. All five ignore NULLs except COUNT(*), which counts rows including those with NULLs in the other columns.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
amount DECIMAL(10, 2) NOT NULL
);
INSERT INTO orders (id, customer_id, amount) VALUES
(1, 1, 120.00),
(2, 1, 340.50),
(3, 2, 75.25),
(4, 2, 610.00);
SELECT COUNT(*) AS row_count,
SUM(amount) AS total,
AVG(amount) AS average,
MIN(amount) AS smallest,
MAX(amount) AS largest
FROM orders;
-- The same aggregates over a set with no matching rows.
SELECT COUNT(*) AS count_empty,
SUM(amount) AS sum_empty,
AVG(amount) AS avg_empty,
MIN(amount) AS min_empty
FROM orders
WHERE customer_id = 999;The first query returns four rows counted, a total of 1145.75, an average of 286.4375, a smallest of 75.25 and a largest of 610.00. The second returns a count of 0 and NULL for every other aggregate — and that asymmetry is worth knowing. COUNT on an empty set is 0 because zero is a meaningful count, while SUM, AVG, MIN and MAX return NULL because there is no value to add up or compare.
That distinction shows up in application code. A report that divides by COUNT assumes it is never zero; if the group is empty, COUNT gives 0 and the division raises an error in most engines. A report that divides by SUM silently produces NULL instead, which usually serialises as a null field in JSON and shows up as a blank in the UI rather than as a crash.
One more trap worth naming: SUM and AVG over a column of integers in SQLite return an integer, so SUM of three 10s gives 30, not 30.0. If you need a decimal result, cast the column to REAL or NUMERIC first. And remember that COUNT(DISTINCT column) is a different beast from COUNT(column) — it counts distinct non-NULL values and needs its own index to be efficient.