Aggregate Functions and Grouping Data in SQL
Aggregate Functions and Grouping Data in SQL
So far, we’ve learned how to retrieve and filter data. But what if you want to summarize large datasets? For example, calculating total sales, average salaries, or counting employees in each department. That’s where aggregate functions and GROUP BY come in.
In this blog, we’ll break down these powerful tools with practical examples.
1. What Are Aggregate Functions?
Aggregate functions perform calculations on multiple rows and return a single value. Common ones include:
| Function | Purpose |
|---|---|
COUNT() | Count rows |
SUM() | Sum of values |
AVG() | Average of values |
MIN() | Minimum value |
MAX() | Maximum value |
Example: COUNT
SELECT COUNT(*) AS total_employeesFROM employees;
-
Counts all employees in the
employeestable. -
Output:
| total_employees |
|---|
| 120 |
Example: SUM
SELECT SUM(salary) AS total_salaryFROM employees;
-
Calculates the total salary of all employees.
Example: AVG, MIN, MAX
SELECT AVG(salary) AS avg_salary,MIN(salary) AS min_salary,MAX(salary) AS max_salaryFROM employees;
-
Returns average, minimum, and maximum salary in a single query.
2. Grouping Data with GROUP BY
GROUP BY lets you summarize data by categories, instead of the whole table.
Example: Count Employees by Department
SELECT department, COUNT(*) AS num_employeesFROM employeesGROUP BY department;
-
Groups employees by
departmentand counts how many are in each.
| department | num_employees |
|---|---|
| Sales | 25 |
| HR | 15 |
| IT | 30 |
Example: Total Salary by Department
SELECT department, SUM(salary) AS total_salaryFROM employeesGROUP BY department;
-
Shows total salaries for each department.
3. Filtering Groups with HAVING
WHERE filters individual rows, but if you want to filter groups, use HAVING.
Example: Departments with More Than 20 Employees
SELECT department, COUNT(*) AS num_employeesFROM employeesGROUP BY departmentHAVING COUNT(*) > 20;
-
Only shows departments with more than 20 employees.
Example: High Salary Departments
SELECT department, AVG(salary) AS avg_salaryFROM employeesGROUP BY departmentHAVING AVG(salary) > 60000;
-
Shows departments with average salary above 60,000.
4. Tips for Using GROUP BY
-
Always include all non-aggregated columns in the
GROUP BYclause. -
Combine
GROUP BYwithORDER BYto sort results. -
Use
HAVINGafter aggregation, unlikeWHERE.
Aggregate functions and GROUP BY are essential for summarizing large datasets. With these, you can:
-
Count records.
-
Calculate totals and averages.
-
Group data by categories.
-
Filter groups using
HAVING.
These tools form the foundation for data analysis in SQL.
Comments
Post a Comment