Aggregate functions are special SQL functions used to perform calculations on a group of rows and return a single summarized result. Instead of showing individual records, aggregate functions help us analyze data by providing totals, averages, minimums, maximums, and counts. These functions are heavily used in reporting, dashboards, analytics, and business decision-making.
Aggregate functions usually work on numeric data, but some of them can also work with dates and text (for example, COUNT).
The COUNT function is used to count the number of rows in a table or the number of non-null values in a column.
SELECT COUNT(*) AS total_employees
FROM employees;
COUNT(*) counts all rows, including rows with NULL valuesSELECT COUNT(*) AS sales_count
FROM employees
WHERE department = 'Sales';
SELECT COUNT(email) AS employees_with_email
FROM employees;
COUNT(column_name) counts only non-null values| Syntax | What It Counts |
|---|---|
| COUNT(*) | All rows |
| COUNT(column) | Non-null values only |
The SUM function is used to calculate the total of numeric values in a column.
SELECT SUM(salary) AS total_salary_cost
FROM employees;
SELECT SUM(salary) AS it_total_salary
FROM employees
WHERE department = 'IT';
The AVG function calculates the arithmetic mean (average) of numeric values.
SELECT AVG(salary) AS average_salary
FROM employees;
SELECT AVG(salary) AS marketing_avg
FROM employees
WHERE department = 'Marketing';
The MIN and MAX functions are used to find the smallest and largest values in a column.
SELECT
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM employees;
SELECT
MIN(hire_date) AS first_hired,
MAX(hire_date) AS last_hired
FROM employees;
Multiple aggregate functions can be used together in a single query.
SELECT
COUNT(*) AS total_employees,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary,
AVG(salary) AS avg_salary,
SUM(salary) AS total_payroll
FROM employees;
This query provides:
This type of query is commonly used in management dashboards.
Example:
SELECT AVG(salary)
FROM employees
WHERE department = 'HR';
Aggregate functions become much more powerful when combined with GROUP BY.
Example:
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
Example:
SELECT department, COUNT(*) AS emp_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
COALESCE() to handle NULLs if neededExample:
SELECT AVG(COALESCE(salary, 0))
FROM employees;