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
    6 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    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.

    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.

    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.

    Real-world use

    Reports like 'orders per country', 'sign-ups per day', 'errors per service' are GROUP BY queries.

    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.

    Hands-on exercise

    Interview preparation — practice these questions:

    • 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.
    Ready to mark this lesson complete?Track your journey across the entire course.