GROUP BY — Complete Guide
GROUP BY — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 13 of 100
GROUP BY
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — SQL & Queries
What is this?
GROUP BY collapses rows sharing the same values in listed columns so you can aggregate — COUNT, SUM, AVG, MAX. Every selected non-aggregated column must appear in GROUP BY.
Why should you care?
Flipkart merchandising asks “revenue per category this month” — one row per category, not millions of line items.
See it live — copy this example
Run in pgAdmin or psql.
SELECT
category,
COUNT(*) AS order_lines,
SUM(line_total) AS revenue
FROM order_items
GROUP BY category
ORDER BY revenue DESC;
What happened?
- Rows with the same category merge into one group.
- COUNT and SUM compute per-group stats.
- ORDER BY sorts the summary, not raw line items.
Practice next
- Create order_items(order_id, category, line_total) with sample data.
- Run the GROUP BY query.
- Try selecting product_name without grouping — read the error.
- Use DATE_TRUNC('month', created_at) in GROUP BY for monthly totals.
- Add COUNT(DISTINCT customer_id) if customer_id is on the table.
Remember
GROUP BY produces one row per distinct group key. Aggregates summarize inside each group. Filter groups with HAVING, not WHERE on aggregates.
PostgresVerse category report
Category managers pull weekly revenue by category for inventory planning.
Outcome: Electronics restock triggers before stockout during sale week.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!