← SQL and databases

Grouping with sorting and several summaries

Rank your groups.

Start this lesson

A grouped query can show several summaries at once, and you can sort the groups with ORDER BY, even by an aggregate. The order of clauses is always SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT. Giving aggregates a name with AS lets you sort by that name.

SELECT author, COUNT(*) AS books, SUM(pages) AS pages
FROM books
GROUP BY author
ORDER BY books DESC, author;

Each author with their number of books and total pages, most books first; authors with the same count are listed A to Z.

Group by an id when names might repeat. Two customers can share a name, but never an id.