PostgreSQL Aggregate Functions
Summary: in this tutorial, you will learn how to use the PostgreSQL aggregate functions such as AVG()
, COUNT()
, MIN()
, MAX()
, and SUM()
.
Introduction to PostgreSQL aggregate functions
Aggregate functions perform a calculation on a set of rows and return a single row. PostgreSQL provides all standard SQL’s aggregate functions as follows:
AVG()
– return the average value.COUNT()
– return the number of values.MAX()
– return the maximum value.MIN()
– return the minimum value.SUM()
– return the sum of all or distinct values.
In practice, you often use the aggregate functions with the GROUP BY
clause in the SELECT
statement:
In this syntax, the GROUP BY
clause divides the result set into groups of rows and the aggregate function performs a calculation on each group e.g., maximum, minimum, average, etc.
PostgreSQL aggregate function examples
Let’s use the film
table in the sample database for the demonstration.
AVG() function examples
The following statement uses the AVG()
function to calculate the average replacement cost of all films:
The following is the result:
Noted that we use the ROUND()
function to round the result to 2 decimal places.
To calculate the average replacement cost of the Drama
films whose category id is 7, you use the following statement:
Here is the result:
COUNT() function examples
To get the number of films, you use the COUNT(*)
function as follows:
Output:
To get the number of drama films, you use the following statement:
The result shows that there are 62 drama films:
MAX() function examples
The following statement returns the maximum replacement cost of films.
Output:
To get the films that have the maximum replacement cost, you use the following query:
Output:
The subquery returned the maximum replacement cost which then was used by the outer query for retrieving the film’s information.
MIN() function examples
The following example uses the MIN()
function to return the minimum replacement cost of films:
Output:
To get the films that have the minimum replacement cost, you use the following query:
Output:
SUM() function examples
The following statement uses the SUM()
function to calculate the total length of films grouped by film’s rating:
The following picture illustrates the result:
Summary
- Aggregate functions perform a calculation on a set of rows and return a single row.
- Use aggregate functions to summarize data.
- Use the
AVG()
function to calculate the average value in a set of values. - Use the
COUNT()
function to perform a count. - Use the
SUM()
function to calculate the total of values. - Use the
MIN()
function to get the minimum value in a set of values. - Use the
MAX()
function to get the maximum value in a set of values.