aggregates

SELECT severity, COUNT(*) AS n
FROM targets
GROUP BY severity
ORDER BY n DESC, severity ASC;

Result:

high     1
low      1
medium   1

Why the second order key

Every group has the same count here ORDER BY n DESC alone leaves ties in an arbitrary order Adding severity ASC makes the output repeatable That matters in tests and in reports

WHERE versus HAVING

WHERE filters rows before grouping HAVING filters groups after grouping

SELECT severity, COUNT(*) AS n
FROM targets
GROUP BY severity
HAVING COUNT(*) > 0;

Common functions

COUNT , SUM , AVG , MIN , MAX COUNT(*) counts rows COUNT(column) skips nulls That difference is a real bug when the column is nullable

Next

All or nothing in 07 transactions

Posted