SQL Tutorial 0/85 lessons ~6 min read Lesson 27

    GROUP BY

    GROUP BY partitions rows into groups so aggregates apply per group.

    Course progress0%
    Focus
    13 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. State the business question GROUP BY answers and the tables involved.
    2. Read the workflow diagram and map each stage to parser, optimizer, or storage.
    3. Write the smallest correct statement (or design change) for a TechLearningPRO Orders/learners dataset.
    4. Predict the failure mode: wrong cardinality, missing index, or unsafe write — then verify.

    Syntax reference

    Visual workflow / architecture:

    bash
    rows
    └─ WHERE filter
    └─ GROUP BY country
    ├─ US ── SUM/COUNT
    ├─ UK ── SUM/COUNT
    └─ IN ── SUM/COUNT
    └─ HAVING filter
    └─ SELECT projection
    Syntax Pattern
    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).
    Live Example
    sql
    SELECT plan, COUNT(*) AS users
    FROM users
    GROUP BY plan;
    users
    idplan
    1free
    2pro
    3pro
    4free
    5pro
    grouped
    planusers
    free2
    pro3
    GROUP BY aggregate
    rows bucketed → SUM/COUNT/AVG

    Rows collapse into one row per group, with aggregates computed.

    Informative example

    Worked SQL example:

    sql
    SELECT plan, COUNT(*) AS users
    FROM users
    GROUP 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 SELECT first.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionQ1. Why must non-aggregated SELECT cols be in GROUP BY?+

    Answer

    GROUP BY = partition rows.
    2IntermediateQuestionQ2. Difference between WHERE and HAVING.+

    Answer

    Aggregates apply per group.
    3IntermediateQuestionQ3. ROLLUP / CUBE — what do they do?+

    Answer

    WHERE before grouping, HAVING after.
    4AdvancedQuestionQ4. How to count distinct per group?+

    Answer

    WHERE before grouping, HAVING after.
    5AdvancedQuestionQ5. Effect of indexes on GROUP BY.+

    Answer

    WHERE before grouping, HAVING after.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.