The SQL Avg() function returns the average value of a numeric column.
SQL Avg() Function Syntax
SELECT AVG(ColumnName) FROM tables WHERE predicates
SQL Avg() Function Example
Table: Employees
| EmployeeId | FirstName | LastName | Department | Salary |
|---|---|---|---|---|
| 203 | Grrhh | Huus | Finance | 78000 |
| 205 | Yrbbg | Bcciu | Finance | 57000 |
| 303 | Aliice | Benyu | Development | 55000 |
| 302 | Yqfgge | Llyqu | Development | 75000 |
We want to know the average salary among all employees:
SELECT AVG(Salary) AS "Average salary" FROM Employees
The result will look like:
| Average salary |
|---|
| 66250 |
Example 2
If we want to select average salary for each department, we can use GROUP BY clause:
SELECT Department, AVG(Salary) AS "Average salary" FROM Employees GROUP BY Department
The result will look like:
| Department | Average salary |
|---|---|
| Finance | 67500 |
| Development | 65000 |
Example 3
If we want to select highest, lowest and average salary for each department:
SELECT Department
, MAX(Salary) AS "Highest salary"
, MIN(Salary) AS "Lowest salary"
, AVG(Salary) AS "Average salary"
FROM Employees
GROUP BY Department
The result will look like:
| Department | Highest salary | Lowest salary | Average salary |
|---|---|---|---|
| Finance | 78000 | 57000 | 67500 |
| Development | 75000 | 55000 | 65000 |
