Starting Postgres in your browser…

Aggregate functions

Aggregate functions boil many rows down to one value: COUNT, SUM, AVG, MIN, and MAX.

Ctrl+Enter to run

One row per group

GROUP BY runs the aggregates once per group instead of once for the whole table. Every column in the SELECT must either be in the GROUP BY or inside an aggregate.

Ctrl+Enter to run

Filter groups with HAVING

WHERE filters rows before they are grouped. HAVING filters the groups afterwards, so it can use aggregates. This finds customers with more than two orders that weren't cancelled.

Ctrl+Enter to run

Try it

exercise Show each order's total (quantity × unit price, added up), largest first. Return two columns: order_id and total. Leave out cancelled orders.

Ctrl+Enter to run