The Wayback Machine - https://web.archive.org/web/20240910140023/https://www.geeksforgeeks.org/aggregate-functions-in-sql/
Open In App

SQL Aggregate functions

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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():

  • Count(*): Returns the total number of records .i.e 6.
  • Count(salary): Return the number of Non-Null values over the column salary. i.e 5.
  • Count(Distinct Salary):  Return the number of distinct Non-Null values over the column salary .i.e 5.  

Sum():

  • sum(salary):  Sum all Non-Null values of Column salary i.e., 3120.
  • sum(Distinct salary): Sum of all distinct Non-Null values i.e., 3120..  

Avg():

  • Avg(salary) = Sum(salary) / count(salary) = 3120 / 5 = 624
  • Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 3120 / 5 = 624

Min():

  • Min(salary): Minimum value in the salary column except NULL i.e., 403.

Max():

  • Max(salary): Maximum value in the salary i.e., 802.  

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:

MySQL
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().

Previous Article
Next Article

Similar Reads

Combining aggregate and non-aggregate values in SQL using Joins and Over clause
Prerequisite - Aggregate functions in SQL, Joins in SQLAggregate functions perform a calculation on a set of values and return a single value. Now, consider an employee table EMP and a department table DEPT with following structure:Table - EMPLOYEE TABLE NameNullTypeEMPNONOT NULLNUMBER(4)ENAME VARCHAR2(10)JOB VARCHAR2(9)MGR NUMBER(4)HIREDATE DATESA
2 min read
How to Use HAVING With Aggregate Functions in SQL?
SQL provides many built-in functions to perform tasks. There are 4 types of functions Date functions, Char functions, Numeric functions, and Aggregate functions. Here we will be looking at aggregate functions and how to use them with the HAVING keyword. Aggregate Functions are database built-in functions that act on multiple rows of the table and p
4 min read
How to Use SELECT With Aggregate Functions in SQL?
In SQL, mainly five aggregate functions are provided. These help us to process the table data in the desired way. All these are illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE Gee
2 min read
Aggregate functions in Cassandra
In this article, we will discuss Aggregate functions in Cassandra which can be used for various purposes such that to count, for finding min and max, sum, etc. Aggregate functions: 1. Count 2. Max and Min 3. Sum 4. Avg In Cassandra, these aggregate functions are pre-defined or in-built functions. Aggregate functions in Cassandra work on a set of ro
3 min read
Filtering Rows Using Aggregate Functions in PostgreSQL
PostgreSQL is an advanced relational database system that supports both relational (SQL) and non-relational (JSON) queries. It is free and open-source. Filtering rows based on conditions is a regular operation in database administration. Although filtering rows by each column value is easily done, more advanced filtering needs which may require agg
5 min read
PHP-My SQL avg() aggregate function
In this article, we are going to find the average of the column in the SQL database using PHP in Xampp server. We are taking an example of a food database to find the average cost of all the items of food. Let's discuss it one by one. Requirements - Xampp server Introduction :Here, we will see the overview of the MySQL and AVG() function. MySQL -My
4 min read
How to Group and Aggregate Data Using SQL?
There can be many columns in a database table, so sometimes it can become difficult and time taking to find the same type of data in these columns. The GROUP BY statement groups the identical rows present in the columns of a table. GROUP BY statement in conjunction with SQL aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG() etc.) help us to a
4 min read
SQL | Difference between functions and stored procedures in PL/SQL
Prerequisite: Procedures in PL/SQLFunctions in PL/SQL.Difference between functions and stored procedures in PL/SQL Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)): 1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and ret
3 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
PHP - MySQL min(),max() aggregate operations
In this article, we are going to find minimum and maximum details from the table column using PHP from MySQL Xampp server. We are taking an example from employee database to find the minimum and maximum salary of the employee. Requirements -Xampp server Introduction : PHP - It stands for Hyper Text Preprocessor which is used to create dynamic web p
4 min read
Aggregate-Oriented Databases in NoSQL
The aggregate-Oriented database is the NoSQL database which does not support ACID transactions and they sacrifice one of the ACID properties. Aggregate orientation operations are different compared to relational database operations. We can perform OLAP operations on the Aggregate-Oriented database. The efficiency of the Aggregate-Oriented database
3 min read
Aggregate Data Model in NoSQL
We know, NoSQL are databases that store data in another format other than relational databases. NoSQL deals in nearly every industry nowadays. For the people who interact with data in databases, the Aggregate Data model will help in that interaction. Features of NoSQL Databases: Schema Agnostic: NoSQL Databases do not require any specific schema or
2 min read
MySQL Aggregate Function
MySQL Aggregate Functions are used to calculate values from multiple rows and return a single result, helping in summarizing and analyzing data. They include functions for counting, summing, averaging, and finding maximum or minimum values, often used with the GROUP BY clause. In this article, we will see different aggregate functions. MySQL Aggreg
3 min read
Functions in MySQL | Numeric, String and Date Time Functions in MySQL
In MySQL, functions play a crucial role in performing various operations on data, such as calculations, string manipulations, and date handling. These built-in functions simplify complex queries and data transformations, making it easier to manage and analyze data within a database. In this article, we will look at these different categories of MyS
4 min read
SQL | Numeric Functions
Numeric Functions are used to perform operations on numbers and return numbers. Following are the numeric functions defined in SQL: ABS(): It returns the absolute value of a number. Syntax: SELECT ABS(-243.5); Output: 243.5 SQL> SELECT ABS(-10); +--------------------------------------+ | ABS(10) +--------------------------------------+ | 10 +---
3 min read
SQL | Advanced Functions
SQL (Structured Query Language) offers a wide range of advanced functions that allow you to perform complex calculations, transformations, and aggregations on your data. Aggregate Functions In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single
2 min read
Date manipulating functions in SQL
To manipulate and fetch date values from the table, oracle has inbuilt date functions. Here, we are going to cover Date manipulating functions in SQL. ADD_MONTHS : It will add the total number of months specified in n to the date parameter and Returns date. Syntax : ADD_MONTHS(d, n) Example - Select ADD_MONTHS(SYSDATE, 4) "Add months" from dual; Ou
2 min read
SQL Server Group Functions
The group function in SQL Server provides a powerful tool for performing calculations on groups of rows, allowing you to group data based on specific criteria. This function is important when you want to analyze and summarize information from multiple records in a data structure. The basic group functions are COUNT, SUM, AVG, MAX, and MIN. Syntax:
3 min read
SQL - Statistical Functions
SQL statistical functions are essential tools for extracting meaningful insights from databases. These functions, such as AVG(), SUM(), COUNT(), MIN(), MAX(), STDDEV(), and VAR(), enable users to perform statistical calculations on numeric data. Whether determining averages, sums, counts, or measures of variability, these functions empower efficien
4 min read
SQL | NULL functions
In the database, null values serve as placeholders for data that is either missing or not available. a null value is a flexible data type that can be placed in the column of any data type, including string, int, blob, and CLOB datatypes. It is not a component of any specific data type. Null values are helpful when cleaning the data prior to explora
5 min read
SQL | Character Functions with Examples
Character functions accept character inputs and can return either characters or number values as output. SQL provides a number of different character datatypes which includes - CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW. The various datatypes are categorized into three different datatypes : VARCHAR2 - A variable-length character datatype whos
6 min read
SQL Server Window Functions ROWS vs. RANGE
We will cover the important concept of the MS SQL Server which is the difference between Row and Range. The confusion between the row and range and where it is used will be eradicated by reading this article. So, be with the flow of the article for a better understanding and keep practicing side by side. Understanding this topic will help you in be
5 min read
Window Functions in PL/SQL
A window function is sometimes referred to as an "Analytic Function". It is generally used to perform calculations on some specific set of rows related to each row in our result set. There are some real-world applications of the window function, they are sales analysis, inventory management, time series analysis, and so on. In short, the window fun
6 min read
How to Find the Length of a Series Using Window Functions in SQL
In data analysis, understanding the sequential patterns within datasets is crucial for informed decision-making. SQL's window functions offer a powerful toolset for such tasks, allowing efficient calculations across related rows. This article delves into utilizing window functions to determine the length of series within datasets. Beginning with an
5 min read
Date and Time Functions in PL/SQL
Date and Time Functions in PL/SQL are useful for date and time operations like extracting date components, performing date arithmetic, and converting between date formats. Date and Time Functions in PL/SQLThere are many useful Date and Time functions in PL/SQL. A table of such functions along with their description is given below: S.noFunctionDescr
4 min read
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() functions are the aggregate functions in SQL, that operate on group of data and return one output. The SQL Min() function returns the minimum value of the selected columns, and the SQL MAX() function is used to return the maximum value of the selected columns. In this article, we will understand the concept of MIN() and MAX(
3 min read
Deterministic and Nondeterministic Functions in SQL Server
Deterministic and nondeterministic functions are two fundamental concepts in SQL Server that determine how a function behaves when called with a specific set of input values. Deterministic functions always return the same result every time they are called with a fixed set of input values and given the same state of the database. On the other hand,
2 min read
PL/SQL Functions
PL/SQL functions are reusable blocks of code that can be used to perform specific tasks. They are similar to procedures but must always return a value. A function in PL/SQL contains:Function Header: The function header includes the function name and an optional parameter list. It is the first part of the function and specifies the name and paramete
4 min read
Article Tags :