Aggregate functions in SQL perform calculations on a set of values and return a single value. These functions are commonly used with the GROUP BY clause, but they can also be used on their own for summarizing data across all rows.
The COUNT() function returns the number of rows in a table, or the number of non-NULL values in a specific column.
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Count the number of employees in the Employees table.
SELECT COUNT(*) AS EmployeeCount
FROM Employees;
EmployeeCount |
---|
100 |
If you want to count only non-NULL values in a specific column:
SELECT COUNT(DepartmentID) AS DepartmentCount
FROM Employees;
The SUM() function adds up the values in a numeric column.Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Find the total sales amount from the Sales table.
SELECT SUM(TotalAmount) AS TotalSales
FROM Sales;
TotalSales |
---|
500000 |
The AVG() function calculates the average of values in a numeric column.
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Calculate the average salary of employees.
SELECT AVG(Salary) AS AverageSalary
FROM Employees;
AverageSalary |
---|
60000 |
The MIN() function returns the smallest value in a column.
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Find the lowest salary in the Employees table.
SELECT MIN(Salary) AS MinSalary
FROM Employees;
MinSalary |
---|
30000 |
The MAX() function returns the largest value in a column.
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Find the highest salary in the Employees table.
SELECT MAX(Salary) AS MaxSalary
FROM Employees;
MaxSalary |
---|
120000 |