MySQL COUNT(), AVG() and SUM() Functions
In this tutorial we will learn about the count(), avg() and sum() functions
Assume the table employee
with the following data to which we will perform these function.
empno | name | age | role | location | salary |
---|---|---|---|---|---|
001 | Andrew | 30 | Manager | India | 100000 |
002 | Beslin | 28 | Business Analyst | India | 50000 |
003 | Joanna | 23 | Senior Developer | USA | 500000 |
004 | Rayan | 26 | Technical Lead | Canada | 500000 |
COUNT() function
The COUNT
function is used to retrieve the number of rows that satisfies the specified criteria.
Syntax for COUNT() function
SELECT COUNT(*)
FROM table_name
WHERE condition;
Example
select count(*) as IndianCount from employee
where location='India';
Output
IndianCount |
---|
2 |
In the above query, we have used alias name IndianCount for the column label to be returned.
The query will return the count of employees who belong to location
India.
SUM() function
The SUM
function will return the sum of a column whose datatype is number or integer.
Syntax for SUM() function
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example
SELECT SUM(salary) as TotalSalary
FROM employee
WHERE location='India';
Output
TotalSalary |
---|
150000 |
The above query will return the total sum of the salary
column whose location
is India.
AVG() Function
The AVG
function is used to return the average value of a column whose type is numeric.
Syntax for AVG() function
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example
SELECT AVG(salary) as AverageSalary
from employee
where location='India';
Output
AverageSalary |
---|
75000 |