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:

FunctionPurpose
COUNT()            Count rows
SUM()            Sum of values
AVG()            Average of values
MIN()            Minimum value
MAX()            Maximum value

Example: COUNT

SELECT COUNT(*) AS total_employees
FROM employees;
  • Counts all employees in the employees table.

  • Output:

total_employees
120

Example: SUM

SELECT SUM(salary) AS total_salary
FROM 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_salary
FROM 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_employees
FROM employees
GROUP BY department;
  • Groups employees by department and 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_salary
FROM employees
GROUP 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_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 20;
  • Only shows departments with more than 20 employees.

Example: High Salary Departments

SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING 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 BY clause.

  • Combine GROUP BY with ORDER BY to sort results.

  • Use HAVING after aggregation, unlike WHERE.

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

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling