What do the GROUP BY and HAVING clauses do, and what are the common aggregate functions like COUNT, SUM, AVG, MIN, and MAX?
Last updated
GROUP BY collapses rows that share the same values into one row per group so aggregate functions can summarize each group, and HAVING filters those resulting groups. Aggregate functions compute a single value across the rows of each group.
GROUP BY: Partitions rows by the listed columns; every non-aggregated column in theSELECTmust appear inGROUP BY.HAVING: Filters the grouped output using aggregate conditions (the group-level counterpart toWHERE).Common aggregates:
COUNT(): number of rows (COUNT(*)counts all,COUNT(col)skipsNULL).SUM()andAVG(): total and mean of numeric values.MIN()andMAX(): smallest and largest value.
Note: most aggregates ignore
NULLvalues (exceptCOUNT(*)).
- https://learn.microsoft.com/en-us/sql/t-sql/functions/aggregate-functions-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql?view=sql-server-ver17
- https://medium.com/@sqlmentor/top-20-sql-group-by-and-having-clause-interview-questions-6a35b8dc33ff
- https://dev.to/pythontutorial/group-by-in-sql-how-to-aggregate-and-analyze-data-efficiently-2be7
- https://blog.devgenius.io/aggregate-queries-in-sql-sum-count-avg-min-max-group-by-having-1201b19c5d86
- https://dbschema.com/blog/tutorials/sql-having-clause/
- https://medium.com/@fatmanurkutlu1/sql-aggregate-functions-and-group-by-ae78dfccbdfa
- https://www.freecodecamp.org/news/sql-aggregate-functions-how-to-group-by-in-mysql-and-postgresql/