MAX() Function in PostgreSQL

In PostgreSQL, the MAX() function computes the maximum of the non-null input values and returns the result.

This function can be used on any numeric, string, date/time, or enum type, as well as inet, interval, money, oid, pg_lsn, tid, and arrays of any of these types.

Example

Here’s a quick example to demonstrate how it works:

SELECT MAX(productprice) 
FROM products;

Result:

245.00

In this case, productprice is a column in the products table.

To give this a bit more context, here’s a snapshot of the table:

+----------+---------------------------------+--------------+
| vendorid |           productname           | productprice |
+----------+---------------------------------+--------------+
|     1001 | Left handed screwdriver         |        25.99 |
|     1001 | Right handed screwdriver        |        25.99 |
|     1001 | Long Weight (blue)              |        14.75 |
|     1001 | Long Weight (green)             |        11.99 |
|     1002 | Sledge Hammer                   |         NULL |
|     1003 | Chainsaw                        |       245.00 |
|     1003 | Straw Dog Box                   |        55.99 |
|     1004 | Bottomless Coffee Mugs (4 Pack) |         9.99 |
+----------+---------------------------------+--------------+

We can see the productprice column for which we got the maximum value in our example.

My actual table contains more columns, but this shows you the column, and its context within the table.

NULL Values

The MAX() function ignores any NULL values. In our sample table above, the sledge hammer has got NULL in its productprice column, but that was ignored in our MAX() example.

Filtered Results

The MAX() function operates on the rows returned by the query. So if you filter the results, the result of MAX() will reflect that.

Lets filter the results:

SELECT MAX(productprice) 
FROM products
WHERE vendorid = 1001;

Result:

25.99

Datetime Values

The MAX() function can be used on datetime values:

Suppose we have a table called pets with the following data:

+-------+---------+------------+
| petid | petname |    dob     |
+-------+---------+------------+
|     1 | Fluffy  | 2020-11-20 |
|     2 | Fetch   | 2019-08-16 |
|     3 | Scratch | 2018-10-01 |
|     4 | Wag     | 2020-03-15 |
|     5 | Tweet   | 2020-11-28 |
|     6 | Fluffy  | 2020-09-17 |
|     7 | Bark    | NULL       |
|     8 | Meow    | NULL       |
+-------+---------+------------+

We can get the maximum value from the dob column, like this:

SELECT MAX(dob) 
FROM pets;

Result:

2020-11-28

Character Data

When used with character data columns, MAX() finds the value that is highest in the collating sequence.

Example:

SELECT MAX(petname) 
FROM pets;

Result:

Wag