GROUP BY
GROUP BY partitions rows into groups so aggregates apply per group.
Introduction
GROUP BY partitions rows into groups so aggregates apply per group. Every SELECT column must either be in GROUP BY or wrapped in an aggregate.
Learning objective: Apply GROUP BY correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.
Treat every example as production-shaped SQL: explicit column lists, deterministic predicates, and indexes that match the access path. Prefer PostgreSQL dialect notes when dialects diverge; call out MySQL differences when they matter.
Purpose of this lesson
Apply GROUP BY correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.
Understanding the topic
Core concepts to understand:
GROUP BY country→ one row per country.GROUP BY country, plan→ one row per (country, plan).- Logical order: WHERE → GROUP BY → HAVING → SELECT.
- Use ROLLUP/CUBE for subtotals (advanced).
- Index helps if cardinality is high.
Step-by-step explanation
- State the business question GROUP BY answers and the tables involved.
- Read the workflow diagram and map each stage to parser, optimizer, or storage.
- Write the smallest correct statement (or design change) for a TechLearningPRO Orders/learners dataset.
- Predict the failure mode: wrong cardinality, missing index, or unsafe write — then verify.
Syntax reference
Visual workflow / architecture:
rows└─ WHERE filter└─ GROUP BY country├─ US ── SUM/COUNT├─ UK ── SUM/COUNT└─ IN ── SUM/COUNT└─ HAVING filter└─ SELECT projection
SELECT <group_col>, <agg_func>(<col>) FROM <table> [WHERE <row_filter>] GROUP BY <group_col>;
GROUP BYBuckets rows that share the same key.agg_funcCOUNT, SUM, AVG, MIN, MAX applied per group.WHEREFilters rows BEFORE grouping (use HAVING for after).
SELECT plan, COUNT(*) AS usersFROM usersGROUP BY plan;
| id | plan |
|---|---|
| 1 | free |
| 2 | pro |
| 3 | pro |
| 4 | free |
| 5 | pro |
| plan | users |
|---|---|
| free | 2 |
| pro | 3 |
Rows collapse into one row per group, with aggregates computed.
Informative example
Worked SQL example:
SELECT plan, COUNT(*) AS usersFROM usersGROUP BY plan;
Real-world use
Reports like 'orders per country', 'sign-ups per day', 'errors per service' are GROUP BY queries.
Security implications
SQL is a trust boundary. Application code must never concatenate untrusted input into statements.
- Use bind parameters / prepared statements — never string-built SQL from request bodies.
- Least-privilege DB roles: app users should not own DDL in production.
- Avoid returning raw DB errors to clients; log server-side with a correlation id.
Best practices
- Group only by indexed/low-cardinality columns when possible.
- Always understand the SELECT/GROUP BY rule — no naked columns.
- Use HAVING to filter post-aggregation, WHERE for pre.
Common mistakes
- Selecting
*in application queries and shipping wide rows over the network. - Filtering on expressions that defeat indexes (
WHERE YEAR(created_at) = 2026). - Running unbounded deletes/updates without a dry-run
SELECTfirst.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionQ1. Why must non-aggregated SELECT cols be in GROUP BY?+
Answer
2IntermediateQuestionQ2. Difference between WHERE and HAVING.+
Answer
3IntermediateQuestionQ3. ROLLUP / CUBE — what do they do?+
Answer
4AdvancedQuestionQ4. How to count distinct per group?+
Answer
5AdvancedQuestionQ5. Effect of indexes on GROUP BY.+
Answer
Hands-on exercise
Hands-on + interview drill:
- Implement the smallest correct example for GROUP BY on an Orders-like schema.
- Q1. Why must non-aggregated SELECT cols be in GROUP BY?
- Q2. Difference between WHERE and HAVING.
- Q3. ROLLUP / CUBE — what do they do?
- Q4. How to count distinct per group?
- Q5. Effect of indexes on GROUP BY.
Summary
GROUP BY is a production SQL skill: state the question, write the precise statement, and prove it with an execution plan or constraint — not with lucky result sets.