SQL - AVG() Function
The AVG() is an aggregate function that is used to find out an average of the list of values of columns or an expression.
The AVG() function is used with the numeric columns only.
Syntax:
SELECT AVG(column_name) FROM table_name WHERE condition;
For the demo purpose, we will use the following Employee
table in all examples here.
EmpId | FirstName | LastName | Salary | DeptId | |
---|---|---|---|---|---|
1 | John | King | '[email protected]' | 24000 | 10 |
2 | James | Bond | 17000 | 20 | |
3 | Neena | Kochhar | '[email protected]' | 15000 | 20 |
4 | Lex | De Haan | '[email protected]' | 9000 | 30 |
5 | Amit | Patel | 60000 | 30 | |
6 | Abdul | Kalam | '[email protected]' | 4800 | 40 |
The following query calculates the average salary of all the employees.
SELECT AVG(Salary) AS AVERAGE FROM Employee;
AVERAGE |
---|
21633 |
You can also calculate the average salary of each department using the following command:
SELECT DeptId, AVG(Salary) AS AVERAGE FROM Employees GROUP BY DeptId;
DeptId | AVERAGE |
---|---|
10 | 24000 |
20 | 16000 |
30 | 34500 |
40 | 4800 |