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
| Concept | Description |
|---|---|
GROUP BY | Groups rows sharing same column values |
| Works with | Aggregate functions like COUNT, SUM, AVG |
| Can group by | One or more columns |
HAVING clause | Filters grouped results (unlike WHERE) |
โ
Use GROUP BY to summarize data by categories