Reference

GROUP BY

Collapse rows into one output row per distinct combination of the grouping keys. Every column in SELECT must either appear in GROUP BY or be wrapped in an aggregate, so the engine knows how to collapse the non-grouped columns.

Syntax #

sql
SELECT key_col, COUNT(*), SUM(metric)
FROM table_name
GROUP BY key_col;

Example #

Loading SQL editor...
Warning

Selecting a non-aggregated column that isn't in GROUP BY is a bug. Strict engines (Postgres, DuckDB, SQL Server) raise an error. Loose engines (MySQL default, older SQLite) return an arbitrary row's value from the group: wrong answer, no warning, no error. Always either include the column in GROUP BY or wrap it in an aggregate (MAX, MIN, STRING_AGG) to make the choice explicit.