Search⌘ K

GROUP BY

Explore how the SQL GROUP BY clause groups rows based on specified columns and enables you to perform aggregate calculations such as COUNT, AVG, and SUM. This lesson helps you understand the syntax and practical usage of GROUP BY in queries, including common errors to avoid and examples of grouping data by attributes like gender or marital status.

We'll cover the following...

GROUP BY

The GROUP BY, as the name suggests, sorts rows together into groups. The clause returns one row for each group. Data is organized using a comma separated list of columns as the criteria specified after the GROUP BY clause. The GROUP BY statement is often used with aggregate functions such as COUNT, MAX, MIN, SUM, and AVG to calculate an aggregated stat for each group.

Syntactically, the GROUP BY clause must appear after the FROM and WHERE clauses and is also evaluated after them. However, GROUP BY is evaluated before the ORDER BY, LIMIT, and HAVING clauses.

Example Syntax

SELECT col1, AggregateFunction(col3) ...