Skip to content
/Chapter 4 · Aggregations and Grouping
Lesson 4.3·garden_shop
Lesson 4.3

SQL GROUP BY: Grouping Rows

GROUP BY changes one overall summary into one summary per group.

Without GROUP BY, an aggregate gives one summary for the whole table. With GROUP BY, SQL creates one summary per category.

The rule is strict: selected columns are either aggregate expressions or columns listed in the GROUP BY clause.

Pattern
select group_column, count(*) as row_count
from table_name
group by group_column
order by row_count desc
Ready to run it?

Open the DuckDB playground with the matching dataset and query already filled in.

What the result should look like

A grouped result has one row per distinct group value. If you group bystatus, each status appears once, and aggregate columns like count(*) describe the rows inside that group.

If SQL complains that a column must appear in the GROUP BY clause, read the SELECT list from left to right. Every plain column needs to be grouped; every summary value needs an aggregate function.

Schema · Garden ShopTable · orders6 columns · 24 rows
Table · orders

One row per order. Unshipped orders have a null shipped_date.

6 columns · 24 rows
order_id intcustomer_id intorder_date dateshipped_date datestatus textcoupon_code text
Your task

Count how many orders are in each status. Sort with the largest groups first.

SQL Workbench
query.sqlgarden_shop · SQL engine loading
⌘↵ to run
·
Expected answer
  • Columns: status, order_count.
  • Rows: 4 status groups.
  • Expected counts: shipped 17, pending 3, processing 3, cancelled 1.