📊 GROUP BY Clause in SQL

Last Updated: January 2026


The GROUP BY clause is used to group rows that have the same values in specified columns and apply aggregate functions on each group.

  • In simple words: It converts many rows into summarized results._
  • Without GROUP BY, aggregate functions work on the entire table. With GROUP BY, they work per category / per group.

Hinglish Tip 🗣: Jab question ho — “har department ka total / average / count chahiye”GROUP BY lagta hai.


🧾 Basic Syntax

SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;

🔑 Important Rule

Every column in SELECT must be either:

  • inside an aggregate function, or
  • mentioned in GROUP BY

❌ This is invalid:

SELECT department, salary
FROM employees
GROUP BY department;

✔ Correct version:

SELECT department, SUM(salary)
FROM employees
GROUP BY department;

Example 1: Count Records Per Group

SELECT department, COUNT(*)
FROM employees
GROUP BY department;

Meaning:

  • Rows are grouped by department
  • Count employees in each department

Example 2: Average Value Per Group

SELECT department, AVG(salary)
FROM employees
GROUP BY department;

✔ Output: One row per department


Example 3: GROUP BY with WHERE

SELECT department, COUNT(*)
FROM employees
WHERE status = 'Active'
GROUP BY department;

Execution order here:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. SELECT