Skip to content

SQL GROUP BY Statement

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_name
WHERE condition
GROUP BY column1
ORDER BY column1;

The examples use the tables from the example database.

The number of productions and the total budget for each format:

SELECT Format, COUNT(*) AS Productions, SUM(Budget) AS TotalBudget
FROM Productions
GROUP BY Format
ORDER 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.

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 Total
FROM Invoices
INNER JOIN Productions ON Invoices.ProductionID = Productions.ProductionID
GROUP BY Productions.Title
ORDER 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

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 Invoices
FROM Productions
LEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionID
GROUP BY Productions.Title
ORDER 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.