GROUP BY Clause Basics
What you'll learn: How to organize query results into groups so you can calculate separate aggregate values for each group instead of one grand total.
The Core Idea
So far, you've learned aggregate functions like COUNT, SUM, AVG, MIN, and MAX — but these produce a single result across all rows. What if you want to compute aggregates for different categories within your data?
That's where GROUP BY comes in. It divides your result set into groups based on the values in one or more columns, then applies aggregate functions to each group separately.
Analogy: Imagine sorting a deck of cards by suit (hearts, diamonds, clubs, spades), then counting how many cards are in each pile. GROUP BY is the sorting step; the aggregate function is the counting.
How It Works
The basic syntax:
SELECT column, AGGREGATE_FUNCTION(another_column)
FROM table
GROUP BY column;
When you use GROUP BY:
- SQL scans your table
- Organizes rows into groups where the
GROUP BYcolumn(s) have the same value - Computes the aggregate function for each group independently
- Returns one row per group
Example:
SELECT department, COUNT(employee_id)
FROM employees
GROUP BY department;
This returns the number of employees in each department, not the total across all departments.
Rules to Remember
- Every column in your
SELECTlist must either be in theGROUP BYclause or wrapped in an aggregate function - You can group by multiple columns:
GROUP BY department, job_title GROUP BYtypically comes afterWHEREbut beforeORDER BY
Key Takeaway: GROUP BY splits your data into subsets based on column values, allowing you to calculate separate aggregate results for each subset rather than one overall total.