All Products
Search
Document Center

MAX

Last Updated: Jun 18, 2021

The MAX function returns the maximum value in the column that is specified by a parameter.

Syntax

MAX([ DISTINCT | UNIQUE | ALL ] expr) [ OVER (analytic_clause) ]

If the function is used as an analytic function, you must use the full syntax of a window function. The function calculates a set of rows and returns multiple values. If the function is used as an aggregate function, the function aggregates a set of rows and returns only one value. In this case, you do not need to add the OVER keyword.

Parameters

Parameter

Description

DISTINCT

Removes duplicate rows from returned rows and ignores the rows whose values are NULL.

UNIQUE

Removes duplicate rows from returned rows and ignores the rows whose values are NULL.

ALL

Returns all the values, including duplicate rows, and ignores the rows whose values are NULL.

expr

The data column or expression of the numeric type, character type, date type, or other types.

OVER

Uses the OVER clause to define a window for calculation.

Return type

The value of the data type same as the data type of expr is returned.

Examples

Examples of the analytic function

The following statements create the employees table and insert data into the table:

CREATE TABLE employees (manager_id INT, last_name varchar(50), hiredate varchar(50), SALARY INT);
INSERT INTO employees VALUES(100, 'Wei',  '2019-09-11',17000);     
INSERT INTO employees VALUES(100, 'Red', '2019-11-05', 17000);
INSERT INTO employees VALUES(101, 'Part',  '2018-10-01',12008); 
INSERT INTO employees VALUES(102, 'Wei',  '2019-09-11',9000);     
INSERT INTO employees VALUES(103, 'Red', '2019-11-05', 6000);
INSERT INTO employees VALUES(104, 'Part',  '2018-10-01',8000); 
COMMIT;

Execute the following statement to query the maximum value in the SALARY column:

SELECT manager_id, last_name, salary FROM (SELECT manager_id, last_name, salary, 
MAX(salary) OVER (PARTITION BY manager_id) AS rmax_sal
FROM employees) WHERE salary = rmax_sal ORDER BY manager_id, last_name, salary;

The following query result is returned:

+------------+-----------+--------+
| MANAGER_ID | LAST_NAME | SALARY |
+------------+-----------+--------+
|        100 | Red       |  17000 |
|        100 | Wei       |  17000 |
|        101 | Part      |  12008 |
|        102 | Wei       |   9000 |
|        103 | Red       |   6000 |
|        104 | Part      |   8000 |
+------------+-----------+--------+

Examples of the aggregate function

Execute the following statement to query the maximum value in the SALARY column:

SELECT MAX(salary) FROM employees;

The following query result is returned:

+-------------+
| MAX(SALARY) |
+-------------+
|       17000 |
+-------------+