PostgreSQL – AVG Function

The AVG function in PostgreSQL is used to calculate the average value of a set of numbers.

The basic syntax of the AVG function is as shown below:

AVG(expression)

In the above syntax, expression represents the column or expression whose average value is to be calculated.

Example: To find the average salary of employees in a table called “employees”, you could use the following query:

SELECT AVG(salary) FROM employees;

This query would return the average value of the “salary” column in the “employees” table.

The AVG function can also be used with the GROUP BY clause to calculate the average value of a column for each group. For example, to find the average salary for each department in the “employees” table, you could use the following query:

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

This query would return the average salary for each department in the “employees” table.

Multiple Columns: You can use the AVG function on multiple columns using below syntax:

SELECT AVG(col1), AVG(col2), AVG(col3) FROM my_table;

Above query would calculate the average value for each of the three columns specified.

Alias: You can use an alias to give the output column a more descriptive name as shown below:

SELECT AVG(salary) AS avg_salary FROM employees;

Above query would give the output column the name avg_salary.

Similar Posts