Postgres max() function
Find the maximum value in a set of values
You can use the Postgres max()
function to find the maximum value in a set of values.
It's particularly useful for data analysis, reporting, and finding extreme values within datasets. You might use max()
to find the product with the highest price in the catalog, the most recent timestamp in a log table, or the largest transaction amount in a financial system.
Function signature
The max()
function has this simple form:
expression
: Any valid expression that can be evaluated across a set of rows. This can be a column name or a function that returns a value.
Example usage
Consider an orders
table that tracks orders placed by customers of an online store. It has columns order_id
, customer_id
, product_id
, and order_date
. We will use this table for examples throughout this guide.
We can use max()
to find the largest order amount:
This query returns the following output:
To find the most recent order date, we compute the maximum value of order_date
:
This query returns the following output:
Advanced examples
Using max() with GROUP BY
You can use max()
with GROUP BY
to find the maximum values in each group:
This query finds the largest order amount for each customer and returns the top 5 customers, sorted in order of the largest order amount.
Using max() with a FILTER clause
The FILTER
clause allows you to selectively include rows in the max()
calculation:
This query calculates both the overall maximum order amount and the maximum order amount for the year 2023.
Finding the row with the maximum value for a column
To retrieve the entire row containing the maximum value, you can use a subquery:
This query returns the full details of the order with the maximum order_amount
.
Using max() with window functions
max()
can be used as a window function to calculate the running maximum over a set of rows:
This query calculates the running maximum order amount over time, showing how the largest order amount changes as new orders come in.
Additional considerations
NULL values
max()
ignores NULL values in its calculations. If all values in the set are NULL, max()
returns NULL.
Performance implications
When used with an index on the column being evaluated, max()
is typically very efficient. The database can often use an index scan to quickly find the maximum value without needing to examine every row in the table. For large datasets, ensure that the column used in the max()
function is properly indexed to maintain good performance.
Alternative functions
min()
: Returns the minimum value in a set of values.greatest()
: Returns the largest value from a list of values/expressions within a single row.
Resources
Last updated on