GROUP BY

Make one result row for each distinct value (or combination of values), then aggregate each group.

Syntax

SELECT column, AGGREGATE(…) FROM table_name GROUP BY column;
  • Every selected column that is not inside an aggregate must be in GROUP BY.

Example

SELECT category, SUM(unit_price) AS total_price FROM products GROUP BY category ORDER BY category;

One row per product category.

Tables used: products. Try it in a lesson below.

Common mistakes

  • A column that is neither grouped nor aggregated is an error in PostgreSQL, even when every row would happen to match.

Practise it