PostgreSQL – MAX Function

In PostgreSQL, the MAX function is used to return the maximum value among a set of values. The syntax of the MAX function is as follows:

SELECT MAX(column_name) FROM table_name;

column_name is the name of the column from which you want to find the maximum value, and table_name is the name of the table in which the column exists.

For example, you can use the below query to find the maximum value in the amount column of orders table.

SELECT MAX(amount) FROM orders;

Above query will return a single value which is the maximum value in the amount column.

The MAX function can be used with multiple columns allowing you to find the maximum value for each column in a table.

SELECT MAX(column1), MAX(column2), MAX(column3) FROM table_name; 

This will return the maximum value for each of the specified columns in the table table_name.

If there are null values in the column you are selecting from, the MAX function will ignore the null values.

MAX function with WHERE clause:

Below is the sql statement to query the maximum value in amount column among a particular customer’s orders

SELECT MAX(amount) FROM orders where customer_id=123;

        MAX function with GROUP BY clause:

        Below is the sql statement to query the maximum value in amount column for every customer.

        SELECT customer_id,MAX(amount) FROM orders group by customer_id;

        Similar Posts