PostgreSQL – AVG (Average) Function

AVG function is an aggregate function that allows you to get the average of values.

Example:

Consider the employee table as shown below:

idfirst_namelast_namedepartmentsalary
101bryanwalkersales50,000
102alexcarpenteraccounts55,000
103samwhitesales60,000
104johnbarrysales54,000
105billwoodaccounts65,000
106roberthopkinssupport70,000
107davidleesupport72,000
108jacksearssupport65,000
109tomyoungsales55,000
employee

You can get the average of all salaries as shown below:

SELECT AVG(salary) FROM employee;

avg
------
60,667

You can use AVG along with the group by clause. Example: To return average of salaries per department, you can group by department as shown below:

SELECT department, AVG(salary) FROM employee GROUP BY department;

department  sum
----------  ---
sales       54,750
accounts    60,000
support     69,000

You can filter grouped results using HAVING clause. Example: Below query returns only the departments that are paying an average salary of more than 60,000 to employees.

SELECT department, SUM(salary) FROM employee GROUP BY department HAVING SUM(salary)>60000;

department  sum
----------  ------
support     69,000
See also  Postgresql - how to declare a variable