Open In App

SQL Aggregate functions

SQL Aggregate functions are functions where the values of multiple rows are grouped as input on certain criteria to form a single value result of more significant meaning.

It is used to summarize data, by combining multiple values to form a single result.

SQL Aggregate functions are mostly used with the GROUP BY clause of the SELECT statement.

Various Aggregate Functions

  1. Count()
  2. Sum()
  3. Avg()
  4. Min()
  5. Max()

Aggregate Functions in SQL

Below is the list of SQL aggregate functions, with examples

Count():

Sum():

Avg():

Min():

Max():

Demo SQL Database

In this tutorial on aggregate functions, we will use the following table for examples:

IdNameSalary
1A802
2B403
3C604
4D705
5E606
6FNULL

You can also create this table on your system, by writing the following queries:

CREATE TABLE Employee (
  Id INT PRIMARY KEY,
  Name CHAR(1),  -- Adjust data type and length if names can be longer than a single character
  Salary DECIMAL(10,2)  -- Adjust precision and scale if needed for salaries
);

INSERT INTO Employee (Id, Name, Salary)
VALUES (1, 'A', 802),
       (2, 'B', 403),
       (3, 'C', 604),
       (4, 'D', 705),
       (5, 'E', 606),
       (6, 'F', NULL);

Aggregate Function Example

In this example, we will use multiple aggregate functions on the data.

Queries

--Count the number of employees
SELECT COUNT(*) AS TotalEmployees FROM Employee;

-- Calculate the total salary
SELECT SUM(Salary) AS TotalSalary FROM Employee;

-- Find the average salary
SELECT AVG(Salary) AS AverageSalary FROM Employee;

-- Get the highest salary
SELECT MAX(Salary) AS HighestSalary FROM Employee;

-- Determine the lowest salary
SELECT MIN(Salary) AS LowestSalary FROM Employee;

Output

TotalEmployees
6
TotalSalary
3120
AverageSalary
624
HighestSalary
802
LowestSalary
403

Key Takeaways about SQL Aggregate Functions

  • Aggregate functions in SQL operate on a group of values and return a single result.
  • They are often used with the GROUP BY clause to summarize the grouped data.
  • Aggregate function operates on non-NULL values only (except COUNT).
  • Commonly used aggregate functions are - MIN(), MAX(), COUNT(), AVG(), and SUM().
Article Tags :