typestar

GROUP BY in SQL

GROUP BY splits rows into buckets and aggregates each bucket.

SELECT
    country,
    plan,
    COUNT(*) AS customers,
    SUM(monthly_total) AS mrr
FROM subscriptions
GROUP BY country, plan
ORDER BY mrr DESC;

How it works

  1. Every non-aggregated column must appear in the GROUP BY.
  2. You can group by more than one column for a cross tabulation.
  3. Ordering by the aggregate ranks the buckets.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
131
Tokens
30
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 21 seconds.

Type this snippet

Step 1 of 4 in Grouping, step 5 of 22 in Joins & aggregation.

← Previous Next →