COUNT, SUM, AVG, MIN, MAX in SQL
SQL COUNT SUM AVG MIN MAX aggregate functions tutorial
SQL aggregate functions allow you to perform calculations on groups of rows and return a single value. These functions are essential when working with reports, analytics, dashboards, and summary data.
In this SQL tutorial, you will learn:
What aggregate functions are
COUNT(), SUM(), AVG(), MIN(), MAX() explained with examples
GROUP BY with aggregates
Real-world use cases
Best practices
Aggregate functions perform calculations on multiple rows and return one result.
Most commonly used aggregate functions are:
COUNT() – counts rows
SUM() – adds values
AVG() – calculates average
MIN() – finds minimum value
MAX() – finds maximum value
Used together with:
SELECT
GROUP BY
HAVING
| id | name | department | salary |
|---|---|---|---|
| 1 | Amit | IT | 50000 |
| 2 | Neha | HR | 45000 |
| 3 | Rahul | IT | 60000 |
| 4 | Sara | HR | 55000 |
| 5 | Karan | Finance | 70000 |
Counts the number of rows in a table or column.
SELECT COUNT(*) AS total_employees
FROM employees;
SELECT COUNT(*) AS it_employees
FROM employees
WHERE department = 'IT';
Calculates total of numeric columns.
SELECT SUM(salary) AS total_salary
FROM employees;
SELECT SUM(salary) AS hr_salary
FROM employees
WHERE department = 'HR';
Finds the average of numeric values.
SELECT AVG(salary) AS average_salary
FROM employees;
SELECT AVG(salary) AS it_average
FROM employees
WHERE department = 'IT';
Finds the smallest value in a column.
SELECT MIN(salary) AS minimum_salary
FROM employees;
Finds the highest value in a column.
SELECT MAX(salary) AS maximum_salary
FROM employees;
Group data and apply aggregate functions.
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
Filter aggregated results.
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 1;
SELECT product_id, SUM(quantity) AS total_sold
FROM sales
GROUP BY product_id;
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id;
SELECT department, MIN(salary), MAX(salary), AVG(salary)
FROM employees
GROUP BY department;
✔ Always use GROUP BY when selecting non-aggregated columns
✔ Use aliases for readability (AS total_salary)
✔ Index columns used in GROUP BY for faster performance
✔ Use HAVING for aggregated conditions after grouping
In this SQL tutorial, you learned:
How COUNT, SUM, AVG, MIN, MAX work
How to summarize data using aggregate functions
How to group results using GROUP BY
Real-world examples used in reporting and analytics
Aggregate functions are essential for business intelligence, dashboards, and database reporting.