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 πΉ Example: Group Employees by Department This query groups employees by department and calculates: πΉ Multiple Columns Grouping Groups data by both department and job title. πΉ Using 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
Was this helpful?
Thanks for your feedback!