SQL GROUP BY

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

๐Ÿ”น Basic Syntax

SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;

๐Ÿ”น Example: Group Employees by Department

SELECT department, COUNT(*) AS total_employees, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;

This query groups employees by department and calculates:

  • Total employees per department
  • Average salary per department

๐Ÿ”น Multiple Columns Grouping

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

Groups data by both department and job title.

๐Ÿ”น Using GROUP BY with HAVING (Filter Groups)

SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Only shows departments with more than 5 employees.

๐Ÿง  Quick Recap

ConceptDescription
GROUP BYGroups rows sharing same column values
Works withAggregate functions like COUNT, SUM, AVG
Can group byOne or more columns
HAVING clauseFilters grouped results (unlike WHERE)

โœ… Use GROUP BY to summarize data by categories