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.
select group_column, count(*) as row_count
from table_name
group by group_column
order by row_count desc 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 by
status, 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 Shop Table · orders 6 columns · 24 rows
One row per order. Unshipped orders have a null shipped_date.
Count how many orders are in each status. Return
status and the count as order_count. Sort with the
largest groups first, and break ties by status.
Run your query to inspect the result.
Expected answer
- Columns: status, order_count.
- Rows: 4 status groups.
- Expected counts: shipped 17, pending 3, processing 3, cancelled 1.
Related
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Avoid truncating fractional results.
Group or aggregate every selected column.
Searched and simple CASE patterns.