Skip to content
SQLSimplified
group by

GROUP BY Multiple Columns

Group by both category and status to see order counts for every product-category/status combination.

Overview

You can GROUP BY more than one column to get finer-grained buckets. The query produces one row per combination of the grouped values. Here we group store orders by product category and order status to see how many orders of each type landed in each state.

The Query

Store (Customers/Orders/Products)

Loading database engine...

Step-by-Step Breakdown

  1. GROUP BY p.category, o.status — buckets are defined by the pair (category, status).
  2. COUNT(*) counts orders in each bucket; SUM(o.quantity) totals units sold in that bucket.
  3. The result has one row per distinct category/status pair that exists.

Order of grouped columns

The order you list columns in GROUP BY doesn't change the buckets, but it does affect the default sort if you don't add an explicit ORDER BY.

Variations

Group by customer city and active status:

Store (Customers/Orders/Products)

Loading database engine...

Common Mistakes

  • Selecting a column you didn't group or aggregate. Every non-aggregated SELECT column must appear in GROUP BY.
  • Too many groups. Adding a high-cardinality column (like an id) to GROUP BY collapses the aggregation back to near one-row-per-input.
  • Confusing WHERE and HAVING. Filter rows before grouping with WHERE; filter groups after with HAVING.

Search

Search lessons, functions, examples, and practice problems