Lesson 3 of 13 · 18 min

GROUP BY: one row per group

By the end of this lesson you can write GROUP BY queries that return one summary row per category, and explain (and fix) the “must appear in the GROUP BY clause” error.

In the last two lessons an aggregate query turned the whole table into one row. Most business questions want a breakdown instead: how many orders per channel? That needs one count for web, one for app and one for marketplace.

GROUP BY channel tells PostgreSQL to sort the rows into groups (think of buckets), one group for each different value of channel. Every aggregate in the SELECT list is then computed separately for each group, and each group becomes one output row.

This is the single most important mental model in reporting: after GROUP BY, you are no longer working with rows, you are working with groups.

Included with a Formula Quest membership

This lesson, its 5 graded exercises and every other Members lesson in SQL Quest come with a Formula Quest membership that includes SQL (Single Quest with SQL selected, Quest Trio including SQL, or Quest Unlimited), or with SQL access from your organization.

Free to everyone: all of SQL Foundations and Retrieving and Filtering Data, the first lesson of every track, the playground, the dataset library and the SQL reference. See free lessons