SQL

GROUP BY — Aggregation Basics

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`GROUP BY` collapses rows into buckets; the SELECT list must be aggregates OR grouped columns. The most common reporting pattern in SQL.
SQL
Raw
-- Orders per user
SELECT user_id,
       COUNT(*)        AS order_count,
       SUM(amount)     AS total_spent,
       MIN(created_at) AS first_order,
       MAX(created_at) AS last_order,
       AVG(amount)     AS avg_order
FROM   orders
GROUP  BY user_id
ORDER  BY total_spent DESC;

-- Group by multiple columns
SELECT country, state, COUNT(*) AS user_count
FROM   users
GROUP  BY country, state
ORDER  BY country, user_count DESC;

-- Group + filter aggregates with HAVING (NOT WHERE — that's per-row)
SELECT user_id, COUNT(*) AS orders
FROM   orders
GROUP  BY user_id
HAVING COUNT(*) > 10        -- only users with > 10 orders
ORDER  BY orders DESC;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.