MySQL is a widely used database management system around the world. Among its features, the MAX function is an important aggregate function that is frequently used in data analysis and report generation. By using this function, you can easily retrieve the maximum value of a specified column. In this article, we will clearly explain everything from the basic usage of MySQL’s MAX function to advanced examples and cautions. The content is aimed at being useful for both beginners and intermediate users, so please use it as a reference.
2. Basic Usage of the MAX Function
The MAX function can be used with various data types such as numbers, dates, and strings. This section provides a detailed explanation of its basic usage.
Syntax of the MAX Function
Below is the basic syntax of the MAX function.
SELECT MAX(column_name) FROM table_name;
Using this syntax, you can retrieve the maximum value of the specified column.
Example Using a Numeric Column
This example retrieves the highest salary from the employees’ salary table.
SELECT MAX(salary) FROM employees;
Output Example:
MAX(salary)
120000
This result shows that the maximum value in the salary column is 120000.
Example Using a Date Column
To retrieve the most recent hire date of employees, write the query as follows.
SELECT MAX(hire_date) FROM employees;
Output Example:
MAX(hire_date)
2025-01-01
From this result, you can see that the latest hire date is 2025-01-01.
Example Using a String Column
The MAX function can also be used on string columns. For strings, it returns the value that appears last in lexical order.
SELECT MAX(last_name) FROM employees;
Output Example:
MAX(last_name)
Yamamoto
This result indicates that the name appearing last in alphabetical (or kana) order is Yamamoto.
3. Retrieving the Maximum Value with Conditions
The MAX function can also be used with conditions. This section explains how to retrieve the maximum value conditionally.
Combining with a WHERE Clause
To retrieve the maximum value for a specific condition, use the WHERE clause. Example: To get the highest salary among employees with department ID 10
SELECT MAX(salary) FROM employees WHERE department_id = 10;
Output Example:
MAX(salary)
90000
This query retrieves the highest salary among employees whose department ID is 10.
Practical Application Example
You can the same syntax to obtain the maximum cost associated with a specific project.
SELECT MAX(cost) FROM projects WHERE project_status = 'active';
This query retrieves the maximum cost for projects that are active.
4. How to Retrieve the Maximum Value per Group
Using MySQL’s GROUP BY clause, you can obtain the maximum value for each specific group. For example, the highest salary per department or the maximum sales per month, which is very handy when grouping and analyzing data. This section provides a detailed explanation of how to retrieve the maximum value per group.
Basic Syntax
To get the maximum value per group, write it as follows.
SELECT group_column, MAX(target_column)
FROM table_name
GROUP BY group_column;
Using this syntax, you group the data based on the specified column and retrieve the maximum value within each group.
Example: Retrieve the Highest Salary per Department
Below is a query that retrieves the highest salary per department from the employees table.
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id;
Sample Output:
department_id
MAX(salary)
1
120000
2
90000
3
80000
This result shows the maximum salary (MAX(salary)) for each department (department_id).
Example: Retrieve the Maximum Sales per Month
To obtain the maximum sales for each month from the sales table, write it as follows.
SELECT DATE_FORMAT(sale_date, '%Y-%m') AS sale_month, MAX(amount)
FROM sales
GROUP BY sale_month;
Sample Output:
sale_month
MAX(amount)
2025-01
50000
2025-02
70000
2025-03
60000
In this query, the sale_date column is formatted to year-month (%Y-%m) and the maximum sales amount is retrieved for each month.
Things to Keep in Mind When Using GROUP BY
Restrictions on Columns Included in SELECT When using the GROUP BY clause, columns in the SELECT statement must be one of the following:
GROUP BY column(s) specified
Aggregate functions (e.g., MAX, SUM, COUNT, etc.) Example: The following query will cause an error.
SELECT department_id, salary
FROM employees
GROUP BY department_id;
Reason: salary is neither an aggregate function nor included in the GROUP BY clause.
Handling of NULL Values If the column being grouped contains NULL values, those NULLs are treated as a separate group. Example: Data with a NULL department ID is calculated as its own group.
Performance Optimization When grouping large amounts of data, leveraging indexes can improve query performance. Set up indexes as needed.
5. How to Retrieve the Entire Record with the Maximum Value
Using MySQL’s MAX function, you can get the maximum value of a specific column, but that alone does not retrieve the entire record that holds the maximum value. In real data analysis and applications, you often need not only the maximum value but also information from related columns. This section explains in detail how to retrieve the entire record that holds the maximum value.
Method 1: Using a Subquery
By using a subquery, you can retrieve the record that has the maximum value of a specific column.
Example: Retrieve Information for the Employee with the Highest Salary
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
Example Output:
employee_id
name
salary
department_id
101
Tanaka
120000
1
How this query works:
The subquery (SELECT MAX(salary) FROM employees) obtains the highest salary.
The outer query retrieves the entire record that has that highest salary.
Method 2: Using JOIN
Using JOIN allows you to create more flexible queries.
Example: Retrieve Information for Employees with the Highest Salary per Department
SELECT e.*
FROM employees e
JOIN (
SELECT department_id, MAX(salary) AS max_salary
FROM employees
GROUP BY department_id
) subquery
ON e.department_id = subquery.department_id AND e.salary = subquery.max_salary;
Example Output:
employee_id
name
salary
department_id
101
Tanaka
120000
1
202
Suzuki
90000
2
How this query works:
The subquery calculates the highest salary for each department.
The main query retrieves the entire record of employees who have that maximum salary.
Method 3: Using Window Functions (MySQL 8.0 and Later)
From MySQL 8.0 onward, you can use window functions to retrieve the record with the maximum value more concisely and efficiently.
Example: Retrieve Employees with the Highest Salary per Department
SELECT employee_id, name, salary, department_id
FROM (
SELECT *,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 1;
Example Output:
employee_id
name
salary
department_id
101
Tanaka
120000
1
202
Suzuki
90000
2
How this query works:
The RANK() function ranks salaries within each department.
The outer query extracts records with a rank of 1 (the records with the maximum value).
Cautions
When Multiple Records Share the Maximum Value
If the maximum value appears in multiple records, both methods will retrieve all matching records. Example:
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
Example Output:
employee_id
name
salary
department_id
101
Tanaka
120000
1
102
Sato
120000
1
Performance Optimization
Using subqueries or JOINs on large datasets can degrade performance.
Properly setting indexes can improve query execution speed.
Practical Use Cases
Retrieve the Product with the Highest Price from a Products Table
SELECT *
FROM products
WHERE price = (SELECT MAX(price) FROM products);
Retrieve Details of the Maximum Cost per Project
SELECT p.*
FROM projects p
JOIN (
SELECT project_id, MAX(cost) AS max_cost
FROM project_costs
GROUP BY project_id
) subquery
ON p.project_id = subquery.project_id AND p.cost = subquery.max_cost;
6. Precautions When Using the MAX Function
MySQL’s MAX function is a very handy aggregate function, but there are several considerations when using it. Understanding the data characteristics, performance, and handling of NULL values helps prevent incorrect results and performance degradation. This section explains in detail the points to watch out for when using the MAX function.
Handling NULL Values
In MySQL, NULL values are treated as “unknown values”. Therefore, when using the MAX function, NULL values are ignored.
Example: Getting the Maximum Value from Data Containing NULLs
SELECT MAX(salary) FROM employees;
Data:
employee_id
name
salary
1
Tanaka
50000
2
Sato
NULL
3
Suzuki
60000
Output:
MAX(salary)
60000
Key Points:
Even if the salary column contains NULL values, the MAX function ignores them in the calculation.
You need to be aware of accurate handling when NULL values are present.
When Multiple Maximum Values Exist
The MAX function returns a single maximum value, but there can be multiple records in the dataset that share the same maximum value. In such cases, you need to craft the query as shown below to retrieve all records with the maximum value.
Example: Retrieving Employees with Multiple Maximum Values
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
Data:
employee_id
name
salary
1
Tanaka
60000
2
Sato
60000
3
Suzuki
50000
Output:
employee_id
name
salary
1
Tanaka
60000
2
Sato
60000
Key Points:
Because the MAX function alone may not suffice, you need to use a subquery to retrieve all relevant records.
Impact on Performance
The MAX function runs quickly for simple queries, but performance can degrade when handling large datasets or complex queries.
Tips for Improving Performance
Utilize Indexes Setting an index on the column used with the MAX function can significantly improve query speed.
CREATE INDEX idx_salary ON employees(salary);
Eliminate Unnecessary Data Use a WHERE clause to narrow down the target data, reducing the amount of data to process.
SELECT MAX(salary)
FROM employees
WHERE department_id = 1;
Calculate in Parts Consider splitting the data into multiple subsets, calculating the maximum for each, and then obtaining the final maximum.
Other Considerations
Impact of Data Types The behavior of the MAX function varies depending on the column’s data type.
Numeric: Simple magnitude comparison.
String: Lexicographical comparison.
Date: Returns the chronologically latest value. Example:
SELECT MAX(last_name) FROM employees;
In this case, the maximum value is returned based on lexicographical order of the strings.
Missing Data Other Than NULL If data is missing, the calculation result may not be as expected. Data cleaning is required.
Combining with Other Aggregate Functions When combining the MAX function with other aggregates (SUM, AVG, etc.), you need to be careful to interpret the results correctly.
7. FAQ: Frequently Asked Questions
We compile and explain the common questions people have about MySQL’s MAX function. This FAQ section covers everything from basic questions to advanced topics.
Q1: Can the MAX function be used on multiple columns at the same time?
A1: No, the MAX function is used on a single column. If you want to get the maximum values of multiple columns, you need to apply the MAX function to each column separately.
Example: Retrieve the maximum values of multiple columns individually
SELECT MAX(salary) AS max_salary, MAX(bonus) AS max_bonus
FROM employees;
Q2: What is the result of the MAX function on a string column?
A2: When the MAX function is applied to a string column, it returns the value that is highest in lexical order.
Example: Get the maximum string value
SELECT MAX(last_name) FROM employees;
Key points:
In lexical order, “Z” comes after “A”, and numbers and symbols are also considered in the evaluation.
If special characters are included, the result may be ordered in an unexpected way.
Q3: What is the difference between the MAX function and the ORDER BY clause?
A3: The MAX function and the ORDER BY clause can be used for similar purposes, but they behave differently.
MAX function: Directly retrieves the maximum value of the specified column.
ORDER BY clause: Sorts the data by the specified column and allows you to retrieve the first or last value as needed.
Example: Retrieve the maximum value using ORDER BY
SELECT * FROM employees
ORDER BY salary DESC
LIMIT 1;
Key points:
The MAX function often offers better performance.
The ORDER BY clause is useful when you need to retrieve the record with the maximum value along with other information.
Q4: Does the MAX function work correctly when NULL values are present?
A4: Yes, the MAX function ignores NULL values. Therefore, the presence of NULLs does not affect the calculation of the maximum.
Example: Behavior when NULL values are present
SELECT MAX(salary) FROM employees;
Data:
employee_id
name
salary
1
Tanaka
60000
2
Sato
NULL
3
Suzuki
50000
Result:
MAX(salary)
60000
Note: If you want to include NULL values in the processing, use the IFNULL function to replace NULL with a default value.
SELECT MAX(IFNULL(salary, 0)) FROM employees;
Q5: Are there ways to improve performance when using the MAX function?
A5: Consider the following methods:
Setting an index: Adding an index to the column used with the MAX function can significantly improve query speed.
CREATE INDEX idx_salary ON employees(salary);
Filtering target data: Use a WHERE clause to limit the data set.
SELECT MAX(salary) FROM employees WHERE department_id = 1;
Query optimization: Eliminate unnecessary calculations and keep the query structure simple.
Q6: What results do you get when combining the MAX function with a GROUP BY clause?
A6: When you combine GROUP BY with the MAX function, you can obtain the maximum value for each group.
Example: Get the highest salary per department
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id;
Result:
department_id
MAX(salary)
1
120000
2
90000
Q7: If there are records with multiple maximum values, how can you retrieve them all?
A7: You can retrieve records that share the maximum value by using subqueries or JOINs.
Example: Retrieve all records with the maximum value
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
Q8: Can the MAX function be used together with window functions?
A8: Yes, starting with MySQL 8.0, you can combine it with window functions for flexible queries.
Example: Retrieve employees with the highest salary per department
SELECT employee_id, name, salary, department_id
FROM (
SELECT *,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 1;
8. Summary
The MySQL MAX function is a very powerful tool for database operations and data analysis. This article comprehensively covered everything from the basic usage of the MAX function to conditional and grouped queries, retrieving records with the maximum value, and performance optimization.
Main Points
Basic Usage of the MAX Function The MAX function is used to retrieve the highest value in a specified column. It works with various data types such as numbers, strings, and dates.
Retrieving Conditional Maximum Values By using the WHERE clause, you can obtain the maximum value that meets specific conditions. This is handy when determining the highest values per project or department.
Getting Maximum Values per Group We also explained in detail how to use the GROUP BY clause to retrieve the maximum value for each group. It can be applied to salaries by department, monthly sales, and more.
Retrieving Entire Records with the Maximum Value You learned how to efficiently fetch whole records that contain the maximum value using subqueries, JOINs, or window functions.
Considerations When Using the MAX Function It’s important to consider how NULL values are handled and the performance impact when multiple rows share the maximum value.
FAQ We provided common questions such as how to use the MAX function on multiple columns and tips for performance optimization.
Conclusion
By using the MAX function effectively, data analysis and report creation become more efficient. Keep studying SQL and practice creating more advanced queries. We hope this article helps deepen your understanding of data manipulation and analysis with MySQL.