;

SQL COUNT, AVG, SUM


SQL has many built-in functions to perform a calculation in SQL. In this tutorial, we will learn how to use COUNT() , AVG() and SUM() functions using SQL.

SQL COUNT, AVG and SUM Functions

COUNT() Function:

COUNT() function in SQL returns the number of rows that match the given criteria in a statement.

Syntax - COUNT() Function
SELECT COUNT(columnName)
FROM tableName
WHERE [CONDITION];

AVG() Function:

AVG() function returns the average value of a numeric column.

Syntax - AVG() Function
SELECT AVG(columnName)
FROM tableName
WHERE [CONDITION];

SUM() Function:

SUM() function returns the total sum of a given numeric column.

Syntax - SUM() Function
SELECT SUM(columnName)
FROM tableName
WHERE [CONDITION];

Example:

Let us consider this table "Employee" for records.

Table Name: Employee

ID EmpName City Country Gender Salary
1 Shankar Delhi India male 25000
2 Sourabh Delhi India male 30000
3 Ranvijay Mumbai India male 15000
4 Kapil Noida India male 25000
5 Shalini Jaipur India female 18000
6 Rakesh Faridabad India male 23000
7 Akshay Mumbai India male 21000
8 Sarah New York US female 76000
9 Rocky Noida India male 28000

Example of COUNT() function

For getting the total number of an employee from the table "Employee", a query will be:

Example - COUNT() Function
SELECT COUNT(EmpName) as TotalEmployee
FROM Employee;
Output
TotalEmployee
9

Example of AVG() Function 

For getting the average salary of an employee from table "Employee", a query will be:

Example - AVG() Function
SELECT AVG(Salary) as AvgSalary
FROM Employee;
Output
AvgSalary
29000

Example of SUM() Function 

For getting the total salary of all employee from table "Employee", a query will be:

Example - SUM() Function
SELECT SUM(Salary) as TotalSalary
FROM Employee;
Syntax - SELECT Statement
TotalSalary
261000