SQL Aggregate Functions

SQL Aggregate Functions perform a calculation on a set of values and return a single value. These functions are often used with the GROUP BY clause to aggregate data.

Common Aggregate Functions

  • COUNT(): Returns the number of rows that match a specified criterion.
  • SUM(): Returns the total sum of a numeric column.
  • AVG(): Returns the average value of a numeric column.
  • MIN(): Returns the minimum value in a set of values.
  • MAX(): Returns the maximum value in a set of values.

Syntax

The basic syntax for using aggregate functions is:


SELECT aggregate_function(column_name)
FROM table_name
WHERE condition;

        

Examples

Here are some examples of using aggregate functions:


-- Count the number of employees
SELECT COUNT(*) AS NumberOfEmployees
FROM Employees;

-- Sum of all sales
SELECT SUM(SaleAmount) AS TotalSales
FROM Sales;

-- Average salary of employees
SELECT AVG(Salary) AS AverageSalary
FROM Employees;

-- Minimum and maximum product prices
SELECT MIN(ProductPrice) AS LowestPrice, MAX(ProductPrice) AS HighestPrice
FROM Products;