MySQL GREATEST() Function
The MySQL GREATEST() function returns the greatest value in a list of expressions. In special cases it returns the following:
- If any of the expression in the list is NULL, then NULL is returned.
Syntax
GREATEST(expr1, expr2, ... expr_n)
Parameters
expr1, expr2, ... expr_n |
Required. Specify the list of expressions to be evaluated. |
Return Value
Returns the greatest value in a list of expressions.
Example 1:
The example below shows the usage of GREATEST() function.
mysql> SELECT GREATEST(20, 30, 60, 10); Result: 60 mysql> SELECT GREATEST('20', '30', '60', '10'); Result: '60' mysql> SELECT GREATEST('D', 'G', 'X', 'A'); Result: 'X' mysql> SELECT GREATEST('Alpha', 'Beta', 'Delta', 'Gamma'); Result: 'Gamma' mysql> SELECT GREATEST('Alpha1', 'Alpha2', 'Alpha3', 'Alpha4'); Result: 'Alpha4' mysql> SELECT GREATEST(20, 30, 60, 10, NULL); Result: NULL
Example 2:
Consider a database table called Sample with the following records:
Data | x | y | z |
---|---|---|---|
Data 1 | 10 | 0 | 11 |
Data 2 | 20 | 15 | 12 |
Data 3 | 30 | 30 | 13 |
Data 4 | 40 | 45 | 14 |
Data 5 | 50 | 60 | 15 |
To get the greatest value, when values of column x, column y and column z are compared, the following query can be used:
SELECT *, GREATEST(x, y, z) AS GREATEST_Value FROM Sample;
This will produce the result as shown below:
Data | x | y | z | GREATEST_Value |
---|---|---|---|---|
Data 1 | 10 | 0 | 11 | 11 |
Data 2 | 20 | 15 | 12 | 20 |
Data 3 | 30 | 30 | 13 | 30 |
Data 4 | 40 | 45 | 14 | 45 |
Data 5 | 50 | 60 | 15 | 60 |
❮ MySQL Functions