SQLSQL
BeginnerLesson 4 of 15

Aggregate Functions, GROUP BY & HAVING – SQL

Summarizing rows: counting, summing, grouping, and filtering groups.

Aggregate functions condense many rows into a single value: COUNT, SUM, AVG, MIN, MAX. COUNT(*) counts all rows, COUNT(column) only rows where the column is not NULL. All aggregates ignore NULL (except COUNT(*)).

SELECT COUNT(*) AS anzahl, MIN(preis) AS minimum, MAX(preis) AS maximum,
       ROUND(AVG(preis), 2) AS schnitt
FROM produkte;
-- anzahl=5, minimum=8.5, maximum=999.0, schnitt=242.5

SELECT COUNT(*) AS alle, COUNT(stadt) AS mit_stadt FROM kunden;   -- 5 and 4

GROUP BY forms groups and applies the aggregates per group. Every column in the SELECT that is not aggregated must appear in GROUP BY. HAVING filters groups after aggregation – WHERE filters rows before it.

SELECT kategorie, COUNT(*) AS n, ROUND(AVG(preis), 2) AS schnitt
FROM produkte
GROUP BY kategorie;

SELECT kategorie, COUNT(*) AS n
FROM produkte
WHERE preis > 10            -- filter rows beforehand
GROUP BY kategorie
HAVING COUNT(*) > 1;        -- only groups with more than one row

The logical order of evaluation explains many error messages: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. That is why an alias from the SELECT may not be used in WHERE (but can be used in ORDER BY).

WarningMySQL used to allow non-aggregated columns without GROUP BY and returned an arbitrary value (ONLY_FULL_GROUP_BY has been on by default since 5.7). SQLite still silently allows it – a breeding ground for bugs.
TipCOUNT(DISTINCT kunde_id) counts distinct values, e.g. how many different customers have placed orders.