Counting and measuring

Lesson 10 of 18 · SQL foundations

An aggregate combines values across rows. COUNT(*) counts rows; COUNT(column) counts non-NULL values. Other common aggregates ignore NULL inputs. With no non-NULL inputs, SUM, AVG, MIN, and MAX return NULL; COUNT returns zero.

SELECT COUNT(*) AS rows_total, COUNT(pages) AS measured,
       SUM(pages) AS total_pages, ROUND(AVG(pages), 1) AS average_pages,
       MIN(pages) AS shortest, MAX(pages) AS longest
FROM books;

The result is (4, 3, 400, 133.3, 80, 200). The average divides 400 by three known values, not four rows. MIN and MAX return values, not necessarily the row that supplied one; use a separate ordered query with a tie-breaker if a row is needed. SQLite has special behavior for bare columns with a single MIN or MAX, but ties remain ambiguous and the pattern is not portable.

Chapter index · Course index