Aggregate Functions
Learn how to use aggregate functions to summarize and analyze data in SQL.
What are Aggregate Functions?
Aggregate functions are used to perform calculations on sets of values, returning a single value. Some common aggregate functions include `COUNT`, `SUM`, `AVG`, `MIN`, and `MAX`. They are typically used with the `GROUP BY` clause to aggregate data based on groups.
Example: Calculating the Average Salary
Let's say you have a table called `Employees` with columns like `EmployeeID`, `Name`, and `Salary`. To calculate the average salary, you would use the following SQL query:
SELECT AVG(Salary) AS AverageSalary FROM Employees;
Example: Using GROUP BY and Aggregate Functions
To calculate the average salary by department, you can use the `GROUP BY` clause:
SELECT Department, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department;
Common Aggregate Functions
COUNT()
: Returns the number of rows in a group.SUM()
: Returns the sum of values in a group.AVG()
: Returns the average of values in a group.MIN()
: Returns the minimum value in a group.MAX()
: Returns the maximum value in a group.