Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctions

MySQL GREATEST Expression

The `GREATEST` expression in MySQL returns the largest value from a list of arguments. It is commonly used to compare multiple values within a row and determine the highest among them.

Usage

The `GREATEST` expression is used when you need to find the maximum value from a set of input values. It is particularly useful in queries where conditional logic is required to evaluate multiple columns or expressions.

GREATEST(value1, value2, ..., valueN)

In this syntax, `GREATEST` takes a list of values or expressions and returns the highest value among them.

Examples

1. Finding the Greatest of Two Numbers

SELECT GREATEST(10, 20) AS max_value;

This example evaluates two numbers, `10` and `20`, and returns `20` as the greatest value.

2. Comparing Column Values

SELECT employee_id, first_name, last_name, GREATEST(salary, bonus) AS max_income
FROM employees;

This query retrieves each employee's ID, name, and the greater value between their `salary` and `bonus`, labeling it as `max_income`.

3. Handling NULL Values

SELECT GREATEST(5, NULL, 12, 8) AS result;

In this example, `GREATEST` returns `NULL` because one of the arguments is `NULL`. If all input values are `NULL`, `GREATEST` will return `NULL`. Note that `SQL_MODE` settings like `IGNORE_SPACE` can alter behavior. Use `COALESCE` to handle `NULL` values and ensure non-NULL results.

4. String and Date Comparisons

SELECT GREATEST('apple', 'banana', 'pear') AS max_string;

In this example, `GREATEST` returns `'pear'` as it is the highest string value alphabetically.

Tips and Best Practices

  • Avoid NULL pitfalls. Be aware that `GREATEST` returns `NULL` if any input value is `NULL`; use `COALESCE` to handle potential `NULL` values.
  • Use with caution in large datasets. `GREATEST` can impact performance on large datasets due to the need to evaluate multiple expressions for each row. Consider optimizing queries or using indexed columns to mitigate performance issues.
  • Ensure consistent data types. The `GREATEST` function performs implicit type conversion among inputs, which can lead to unexpected results. Ensure arguments are of comparable types to avoid type conversion errors.
  • Combine with conditional logic. Use `GREATEST` in conjunction with other conditional expressions for more complex logic within your queries.