GROUP BY sorts rows into groups that share a value, and turns each group into one row of the result. With a function such as COUNT(), SUM() or AVG(), it answers questions like “how many of each” or “how much per”.
SELECT column1, COUNT(*)FROM table_nameWHERE conditionGROUP BY column1ORDER BY column1;The examples use the tables from the example database.
A summary for each group
Section titled “A summary for each group”The number of productions and the total budget for each format:
SELECT Format, COUNT(*) AS Productions, SUM(Budget) AS TotalBudgetFROM ProductionsGROUP BY FormatORDER BY TotalBudget DESC;| Format | Productions | TotalBudget |
|---|---|---|
| Drama series | 2 | 29,500,000 |
| Feature film | 2 | 11,100,000 |
| Documentary | 1 | 850,000 |
Each format appears once, and the functions work on that format’s rows only. ORDER BY can sort on a summary column by its alias.
Groups from a join
Section titled “Groups from a join”Join first, then group. The number of invoices and the amount invoiced for each production:
SELECT Productions.Title, COUNT(*) AS Invoices, SUM(Invoices.Amount) AS TotalFROM InvoicesINNER JOIN Productions ON Invoices.ProductionID = Productions.ProductionIDGROUP BY Productions.TitleORDER BY Total DESC;| Title | Invoices | Total |
|---|---|---|
| The Lantern Keepers | 2 | 65,850.00 |
| Quarry Lane | 1 | 3,180.00 |
| Six Bells | 1 | 2,940.00 |
Groups with nothing in them
Section titled “Groups with nothing in them”The inner join above leaves out the productions with no invoices. To list them with a count of zero, start from Productions, use a left join, and count a column from the invoice side:
SELECT Productions.Title, COUNT(Invoices.InvoiceID) AS InvoicesFROM ProductionsLEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionIDGROUP BY Productions.TitleORDER BY Invoices DESC, Productions.Title;| Title | Invoices |
|---|---|
| The Lantern Keepers | 2 |
| Quarry Lane | 1 |
| Six Bells | 1 |
| Fennick’s Return | 0 |
| Saltmarsh | 0 |
COUNT(Invoices.InvoiceID) counts only rows where an invoice was found, so the unmatched productions score zero. COUNT(*) would have counted their one empty row and given them 1.
To filter on a group’s summary, such as only the productions with more than one invoice, use HAVING.