TopicsCheat sheetLessons
Lurndo › Topics › GROUP BY

Learn SQL: GROUP BY

Per group with GROUP BY

"One total is nice," says Lien, "but which type of bike brings in the most? And which country do the best customers come from?" That's not one number, but one number per group.

GROUP BY makes groups

GROUP BY type puts all the bikes of the same type on one pile. The aggregate function then works per pile: you get one row per type, with the number of bikes of that type.

SELECT type, COUNT(*) AS number FROM bikes GROUP BY type
Result
typenumber
cargo bike2
city bike6
e-bike4
kids bike2
tandem2

One rule for your columns

With GROUP BY, every column in your SELECT can only be one of two things: a column you group by, or an aggregate function such as SUM.

Add another column and SQLite won't complain, but it picks an arbitrary value from the group. Other databases give an error. Here's the revenue per bike type.

SELECT bike_type, SUM(amount) AS revenue FROM rentals GROUP BY bike_type
Result
bike_typerevenue
cargo bike244
city bike239
e-bike1029
kids bike24
tandem165

Several columns, and sorting

You can group by several columns: then every combination is a group, just like with DISTINCT. Here's the number of bikes per type and brand.

GROUP BY comes after WHERE and before ORDER BY. You can also sort on the result of a function, such as ORDER BY COUNT(*) DESC.

SELECT type, brand, COUNT(*) AS number FROM bikes GROUP BY type, brand ORDER BY type
Result
typebrandnumber
cargo bikeBabboe1
cargo bikeUrban Arrow1
city bikeBatavus2
city bikeGazelle2
city bikeOxford2
e-bikeGazelle1
e-bikeOxford1
e-bikeStromer2

Try it yourself

Show the revenue per country, with the country with the highest revenue at the top.

Ready for more?

The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.

Start the lesson
← PreviousThe smallest and the largestNext →Filtering groups with HAVING
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands