The GREATEST() function in MySQL is used to return the greatest (largest) value from a list of arguments. It evaluates each argument and returns the one with the highest value.
Syntax
GREATEST(arg1, arg2, arg3, ...)
Definition and Usage
- The
GREATEST()function compares two or more values and returns the largest value in the list. - If any argument is
NULL, the result will beNULL. - The function works for numeric, string, and date types, but the comparison is done based on the data type and the values' order.
Parameter Values
| Parameter | Description |
|---|---|
arg1, arg2, arg3, ... |
Required. A list of arguments to be compared. These can be numbers, strings, or dates. |
Technical Details
- Works in: From MySQL 4.0
- Return Value: The greatest value from the list of arguments.
Examples
Example 1: Return the greatest value of a list of numbers
SELECT GREATEST(3, 12, 34, 8, 25);
Result:
GREATEST(3, 12, 34, 8, 25): 34
Explanation: The function returns 34, which is the largest number in the list.
Example 2: Return the greatest value from a list of strings
SELECT GREATEST("w3Schools.com", "microsoft.com", "apple.com");
Result:
GREATEST("w3Schools.com", "microsoft.com", "apple.com"): "w3Schools.com"
Explanation: The function compares the strings lexicographically (alphabetically) and returns "w3Schools.com" as it comes last in alphabetical order.
Example 3: Return the greatest date value
SELECT GREATEST('2024-12-01', '2024-12-15', '2024-12-10');
Result:
GREATEST('2024-12-01', '2024-12-15', '2024-12-10'): '2024-12-15'
Explanation: The function returns '2024-12-15' as it is the latest date.
Usage Notes
- The
GREATEST()function is useful for selecting the maximum value from multiple expressions or columns. - When dealing with strings, it compares them in lexicographical order.
- For date values, the function returns the latest date.
- If any argument is
NULL, the result will beNULL, so it's often good practice to ensure thatNULLvalues are handled properly usingIFNULL()orCOALESCE().
This function is commonly used for finding the highest value in a set of values, such as finding the maximum salary, date, or number from a collection of records.