GROUP BY — Complete Guide
GROUP BY — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 13 of 100
GROUP BY
Basics → Advanced
Basics · 1 — SQL · ~6 min · MySQL — Queries & Clauses
What is this?
GROUP BY collapses rows that share the same column values into one summary row. You use it with aggregates like COUNT or SUM to answer “per city” or “per day” questions.
Why should you care?
Swiggy ops needs “orders per restaurant per hour”, not a flat list of ten million order rows.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
SELECT city, COUNT(*) AS customer_count
FROM customers
GROUP BY city
ORDER BY customer_count DESC;
What happened?
- Rows with the same city merge into one group.
- COUNT(*) counts members per city.
- ORDER BY sorts cities by popularity.
- Non-grouped columns cannot appear unless aggregated.
Practice next
- Add customers in 4+ cities.
- Run GROUP BY city.
- Add HAVING customer_count > 1 in the next lesson style.
- GROUP BY DATE(created_at) for signups per day.
- Use COUNT(DISTINCT city) vs COUNT(*) and compare.
Remember
GROUP BY builds buckets of rows. Every selected non-aggregated column must be in GROUP BY. Pair with COUNT/SUM/AVG for metrics.
DataFlow signup map
Growth team charts new customers per city weekly from one GROUP BY query.
Outcome: Marketing spends where signups actually happen.
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!