Course contentsShow
← Computer Science
Lesson 1595 of 2,87236. Database FundamentalsFree lesson

GROUP BY Clause Basics

Grouping rows by one or more columns to compute aggregates for each group separately.

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:

  1. SQL scans your table
  2. Organizes rows into groups where the GROUP BY column(s) have the same value
  3. Computes the aggregate function for each group independently
  4. 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 SELECT list must either be in the GROUP BY clause or wrapped in an aggregate function
  • You can group by multiple columns: GROUP BY department, job_title
  • GROUP BY typically comes after WHERE but before ORDER 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.