MySQL
SQL Functions
MAX Function
Database Query
SQL Tutorial

How to get the max of two values in MySQL?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

MySQL, a relational database management system, allows users to perform various operations using SQL (Structured Query Language). One common task is to determine the maximum value between two given numbers. This can be easily achieved using the built-in SQL function GREATEST(). In this article, we will explore how to use this function, enhance our queries, and discuss related subtopics.

Using the GREATEST() Function

Basic Usage

The GREATEST() function is the most straightforward way to find the maximum value between two or more numerical values in MySQL. The syntax is:

sql
GREATEST(value1, value2, [value3, ...])

Example:

To find the maximum value between two numbers:

sql
SELECT GREATEST(12, 35) AS max_value;

This query will return:

max_value
35

Handling Multiple Values

The GREATEST() function can handle more than two values, returning the largest value among all specified:

Example:

sql
SELECT GREATEST(5, 10, 15, 20, 25) AS max_value;

This returns:

max_value
25

NULL Values Handling

If any of the provided values are NULL, the GREATEST() function will return NULL unless using COALESCE to handle nullability:

Example:

sql
1SELECT GREATEST(10, NULL, 3) AS max_value;  -- Returns NULL
2
3-- Handling NULLs with COALESCE
4SELECT GREATEST(10, COALESCE(NULL, 0), 3) AS max_value;  -- Returns 10

Practical Applications

Comparing Column Values

When comparing values stored in columns across a table, GREATEST() is beneficial. Suppose we have a table student_scores with columns math_score and english_score.

Example:

sql
1CREATE TABLE student_scores (
2    student_id INT,
3    math_score INT,
4    english_score INT
5);
6
7INSERT INTO student_scores (student_id, math_score, english_score)
8VALUES (1, 85, 92), (2, 78, 80), (3, 90, 86);
9
10SELECT student_id, GREATEST(math_score, english_score) AS highest_score
11FROM student_scores;

This query finds the highest score for each student.

student_idhighest_score
192
280
390

Performance Considerations

While GREATEST() is efficient for scalar values, its performance when used in large datasets should be considered, especially if combined with complex queries. Indexing the columns involved can enhance performance significantly.

COALESCE for NULL Management

COALESCE() is useful to return the first non-null value among multiple arguments, often used in tandem with GREATEST() when handling potential NULL values. It ensures that operations do not yield premature NULL results.

MySQL Stored Functions

If more complex logic is required for finding maximum values, MySQL allows users to create stored functions. However, for straightforward comparisons, GREATEST() remains the optimal choice.

sql
1DELIMITER //
2
3CREATE FUNCTION max_number(a INT, b INT)
4RETURNS INT
5BEGIN
6    RETURN GREATEST(a, b);
7END //
8
9DELIMITER ;

This custom function expands GREATEST() for specific use cases when predefined logic is needed.

Common Pitfalls

  • Using MAX() when you really need GREATEST() for scalar comparison in one row.
  • Forgetting that GREATEST() returns NULL if any argument is NULL unless you normalize inputs first.
  • Comparing string columns without checking collation and implicit type conversion rules.
  • Using scalar comparison logic in WHERE clauses without considering how it affects indexes and execution plans.
  • Treating a simple two-value comparison as trivial even when nullability and mixed types can change the result.

Summary

  • Use GREATEST() to compare two or more scalar values in one MySQL expression.
  • Prefer COALESCE() when nullable inputs should not force the whole result to NULL.
  • Apply the same pattern to column values when you need the larger value from the same row.
  • Validate collation, type conversion, and null rules before trusting the output.
  • Keep the comparison logic explicit so later query changes stay correct.

Course illustration
Course illustration

All Rights Reserved.