In this PostgreSQL post explains how to use the PostgreSQL avg function with syntax and examples.
The PostgreSQL avg function returns the average value of an expression.
The syntax for the avg function in PostgreSQL is:
OR the syntax for the avg function when grouping the results by one or more columns is:
Expressions that are not encapsulated within the avg function and must be included in the GROUP BY clause at the end of the SQL statement.
This is the column or expression that will be averaged.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. These are conditions that must be met for the records to be selected.
The avg function can be used in the following versions of PostgreSQL:
Let's look at some PostgreSQL avg function examples and explore how to use the avg function in PostgreSQL.
For example, you might wish to know how the average quantity in inventory.
In this avg function example, we've aliased the avg(quantity) expression as "Average Quantity". As a result, "Average Quantity" will display as the field name when the result set is returned.
You can use the DISTINCT clause within the avg function. For example, the SQL statement below returns the average quantity of unique quantity values where the product_type is 'Hardware'.
If there were two quantities of 25, only one of these values would be used in the avg function.
The expression contained within the avg function does not need to be a single field. You could also use a formula. For example, you might want the average commission.
You could also use the avg function to return the department and the average quantity (in the associated department). For example,
Because you have listed one column in your SELECT statement that is not encapsulated in the avg function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.