Menu
CoddyTech

Group by Category

Part of the SQL Foundations section of Coddy's PostgreSQL journey. Lesson 13 of 22.

GROUP BY partitions rows by equal key values before calculating aggregates. Select a grouping key together with summaries. A selected ordinary column must be grouped or otherwise be valid under PostgreSQL grouping rules.

Input table products:

idnamecategorypricestockactivenote
1Maptravel125TrueNULL
2Notebookbooks80TrueRecycled
3Atlasbooks243FalseNULL
4Mughome128TrueBlue
5lamphome302FalseClearance
6Mini maptravel610TrueNULL
SELECT category, COUNT(*) AS product_count FROM products GROUP BY category ORDER BY category;

Each category produces one row and has two products in the sample. GROUP BY changes the result grain from one row per product to one row per category. ORDER BY separately controls display order.

Group by the keys that define one output row; aggregate the values within each group.

challenge icon

Challenge

Medium

Return category and total_stock for each category. Sum stock and order by category.

The input tables are shown in the test panel. Each run starts from fresh data. Return the named columns in the stated order; do not hard-code the displayed rows.

Try it yourself

-- Write your SQL here.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in SQL Foundations

Practice on your own: PostgreSQL playground