MySQL MAX Function Explained: Syntax, Examples, GROUP BY, and Performance Optimization

目次

1. Introduction

MySQL is a database management system widely used around the world. Among its many features, the MAX function is an important aggregate function frequently used in data analysis and report generation. By using this function, you can easily retrieve the maximum value of a specified column.

This article clearly explains everything from the basic usage of the MySQL MAX function to advanced examples and important considerations. It is designed to be helpful for both beginners and intermediate users, so be sure to use it as a reference.

2. Basic Usage of the MAX Function

The MAX function can be used with various data types, including numeric values, dates, and strings. In this section, we will explain the basic usage in detail.

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 MAX with a Numeric Column

The following example retrieves the highest salary from the employees table.

SELECT MAX(salary) FROM employees;

Output Example:

MAX(salary)
120000

This result indicates that the maximum value in the salary column is 120000.

Example: Using MAX with a Date Column

To retrieve the most recent hire date of employees, use the following query:

SELECT MAX(hire_date) FROM employees;

Output Example:

MAX(hire_date)
2025-01-01

This result shows that the most recent hire date is 2025-01-01.

Example: Using MAX with a String Column

The MAX function can also be used with string columns. For strings, it returns the value that appears last in lexicographical (dictionary) order.

SELECT MAX(last_name) FROM employees;

Output Example:

MAX(last_name)
Yamamoto

This result indicates that Yamamoto is the name that appears last in alphabetical (lexicographical) order.

3. Retrieving the Maximum Value with Conditions

The MAX function can also be used with conditions. In this section, we explain how to retrieve a maximum value under specific conditions.

Combining with the WHERE Clause

To retrieve the maximum value with specific conditions, use the WHERE clause.

Example: Retrieve the highest salary among employees whose department ID is 10

SELECT MAX(salary) FROM employees WHERE department_id = 10;

Output Example:

MAX(salary)
90000

This query retrieves the maximum salary among employees whose department ID is 10.

Practical Business Example

You can use the same syntax to retrieve the maximum cost related to a specific project.

SELECT MAX(cost) FROM projects WHERE project_status = 'active';

This query retrieves the maximum cost among projects with active status.

4. How to Retrieve the Maximum Value for Each Group

By using MySQL’s GROUP BY clause, you can retrieve the maximum value for each group. For example, this is very useful when analyzing data by grouping, such as the highest salary per department or the maximum sales per month. In this section, we explain how to retrieve maximum values by group in detail.

Basic Syntax

To retrieve the maximum value for each group, write the query as follows:

SELECT grouping_column, MAX(target_column)
FROM table_name
GROUP BY grouping_column;

With this syntax, MySQL groups the data based on the specified column and returns the maximum value within each group.

Example: Retrieve the Highest Salary per Department

The following query retrieves the highest salary per department from the employees table.

SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id;

Output Example:

department_idMAX(salary)
1120000
290000
380000

This result shows the maximum salary (MAX(salary)) for each department (department_id).

Example: Retrieve the Maximum Sales per Month

To retrieve the maximum sales amount for each month from a sales table, write the query as follows:

SELECT DATE_FORMAT(sale_date, '%Y-%m') AS sale_month, MAX(amount)
FROM sales
GROUP BY sale_month;

Output Example:

sale_monthMAX(amount)
2025-0150000
2025-0270000
2025-0360000

In this query, the sale_date column is formatted into year-month (%Y-%m), and the maximum sales amount is retrieved for each month.

Important Notes When Using GROUP BY

  1. Restrictions on Columns Included in the SELECT Statement
    When using the GROUP BY clause, columns included in the SELECT statement must be one of the following:
  • Columns specified in the GROUP BY clause
  • Aggregate functions (e.g., MAX, SUM, COUNT, etc.) Example: The following query will result in an error.
   SELECT department_id, salary
   FROM employees
   GROUP BY department_id;

Reason: salary is not included in an aggregate function or the GROUP BY clause.

  1. Handling NULL Values
    If the grouping column contains NULL values, those NULL values are treated as a separate group. Example: Records with a NULL department ID are also calculated as one group.
  2. Performance Optimization
    When grouping large amounts of data, using indexes can improve query performance. Add indexes as needed.

5. How to Retrieve the Entire Record with the Maximum Value

Using the MySQL MAX function allows you to retrieve the maximum value of a specific column. However, it does not automatically return the entire record that contains that maximum value. In real-world data analysis and applications, you often need not only the maximum value itself but also related information from other columns.

In this section, we explain in detail how to retrieve the entire record that contains the maximum value.

Method 1: Using a Subquery

You can use a subquery to retrieve records that contain the maximum value in a specific column.

Example: Retrieve Information for the Employee with the Highest Salary

SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

Output Example:

employee_idnamesalarydepartment_id
101Tanaka1200001

How this query works:

  1. The subquery (SELECT MAX(salary) FROM employees) retrieves the highest salary.
  2. The outer query retrieves the entire record that matches that highest salary.

Method 2: Using JOIN

Using JOIN allows you to create more flexible queries.

Example: Retrieve 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;

Output Example:

employee_idnamesalarydepartment_id
101Tanaka1200001
202Suzuki900002

How this query works:

  1. The subquery calculates the highest salary for each department.
  2. The main query retrieves the full employee records that match those maximum salaries.

Method 3: Using Window Functions (MySQL 8.0+)

In MySQL 8.0 and later, you can use window functions to retrieve records 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;

Output Example:

employee_idnamesalarydepartment_id
101Tanaka1200001
202Suzuki900002

How this query works:

  1. The RANK() function ranks salaries within each department in descending order.
  2. The outer query extracts records where the rank is 1 (records with the maximum value).

Important Notes

  1. If Multiple Records Share the Maximum Value
  • If multiple records share the same maximum value, all matching records will be returned by either method. Example:
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

Output Example:

employee_idnamesalarydepartment_id
101Tanaka1200001
102Sato1200001
  1. Performance Optimization
  • Using subqueries or JOINs on large datasets may reduce performance.
  • Proper indexing can significantly improve query execution speed.

Practical Business Examples

  1. Retrieve the Product with the Highest Price
SELECT *
FROM products
WHERE price = (SELECT MAX(price) FROM products);
  1. Retrieve Detailed Information 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. Important Considerations When Using the MAX Function

The MySQL MAX function is a very useful aggregate function, but there are several important points to keep in mind when using it. Understanding data characteristics, performance implications, and how NULL values are handled helps prevent incorrect results and performance degradation. In this section, we explain the key considerations 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: Retrieving the Maximum Value from Data Including NULL

SELECT MAX(salary) FROM employees;

Data:

employee_idnamesalary
1Tanaka50000
2SatoNULL
3Suzuki60000

Output:

MAX(salary)
60000

Key Points:

  • Even if the salary column contains NULL values, the MAX function ignores them during calculation.
  • You should carefully consider how NULL values affect your data logic.

When Multiple Maximum Values Exist

The MAX function returns a single maximum value, but multiple records may share that same maximum value in the dataset. In such cases, you need to structure the query to retrieve all matching records.

Example: Retrieve Employees with the Same Maximum Salary

SELECT * 
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

Data:

employee_idnamesalary
1Tanaka60000
2Sato60000
3Suzuki50000

Output:

employee_idnamesalary
1Tanaka60000
2Sato60000

Key Point:

  • If MAX alone is not sufficient, use a subquery to retrieve all matching records.

Performance Impact

The MAX function performs efficiently in simple queries. However, performance may degrade when working with large datasets or complex queries.

Tips for Improving Performance

  1. Use Indexes
    Adding an index to the column used in the MAX function can significantly improve query speed.
CREATE INDEX idx_salary ON employees(salary);
  1. Filter Unnecessary Data
    Reduce the dataset by using a WHERE clause to limit the target rows.
SELECT MAX(salary)
FROM employees
WHERE department_id = 1;
  1. Divide and Compute
    Consider calculating maximum values in subsets and then determining the final maximum.

Other Considerations

  1. Impact of Data Types
    The behavior of the MAX function depends on the column’s data type.
  • Numeric: Simple numerical comparison.
  • String: Compared in lexicographical order.
  • Date: Returns the most recent (latest) date. Example:
SELECT MAX(last_name) FROM employees;

In this case, the maximum value is determined based on lexicographical string order.

  1. Missing Data Other Than NULL
    If data is incomplete or improperly formatted, the calculation result may not match expectations. Data cleaning may be necessary.
  2. Combining with Other Aggregate Functions
    When combining MAX with other aggregate functions (such as SUM or AVG), ensure that you correctly interpret the results.

7. FAQ: Frequently Asked Questions

This section summarizes and explains common questions about the MySQL MAX function. It covers both basic and advanced topics.

Q1: Can the MAX function be used on multiple columns at the same time?

A1: No, the MAX function operates on a single column. If you want to retrieve the maximum values of multiple columns, you must apply the MAX function to each column individually.

Example: Retrieve Maximum Values from Multiple Columns

SELECT MAX(salary) AS max_salary, MAX(bonus) AS max_bonus
FROM employees;

Q2: What happens when the MAX function is applied to a string column?

A2: When applied to a string column, the MAX function returns the value that is last in lexicographical (dictionary) order.

Example: Retrieve the Maximum String Value

SELECT MAX(last_name) FROM employees;

Key Points:

  • In lexicographical order, “Z” comes after “A”, and numbers and symbols are also evaluated.
  • If special characters are included, the result may not match your expected order.

Q3: What is the difference between the MAX function and the ORDER BY clause?

A3: Although the MAX function and ORDER BY clause may appear to serve similar purposes, they behave differently.

  • MAX function: Directly retrieves the maximum value of the specified column.
  • ORDER BY clause: Sorts data based on 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 is often more efficient in terms of performance.
  • The ORDER BY clause is useful when you need additional information along with the record containing the maximum value.

Q4: Does the MAX function work correctly when NULL values are included?

A4: Yes, the MAX function ignores NULL values. Therefore, NULL values do not affect the maximum value calculation.

Example: Behavior When NULL Values Are Included

SELECT MAX(salary) FROM employees;

Data:

employee_idnamesalary
1Tanaka60000
2SatoNULL
3Suzuki50000

Result:

MAX(salary)
60000

Important Note:
If you want to include NULL values in processing, use the IFNULL function to replace NULL with a default value.

SELECT MAX(IFNULL(salary, 0)) FROM employees;

Q5: How can I improve performance when using the MAX function?

A5: Consider the following approaches:

  1. Add Indexes: Adding an index to the column used in the MAX function can significantly improve query performance.
CREATE INDEX idx_salary ON employees(salary);
  1. Filter Target Data: Use a WHERE clause to reduce the number of rows processed.
SELECT MAX(salary) FROM employees WHERE department_id = 1;
  1. Optimize Queries: Eliminate unnecessary calculations and keep the query structure simple.

Q6: What happens when combining MAX with the GROUP BY clause?

A6: When combining GROUP BY with the MAX function, you can retrieve the maximum value for each group.

Example: Retrieve the Highest Salary per Department

SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id;

Result:

department_idMAX(salary)
1120000
290000

Q7: If multiple records share the maximum value, how can I retrieve all of them?

A7: Use a subquery or JOIN to retrieve all records that share the maximum value.

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, in MySQL 8.0 and later, you can combine MAX with window functions for more 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 powerful tool for database operations and data analysis. In this article, we comprehensively covered everything from the basic usage of the MAX function to conditional queries, grouping, retrieving entire records with maximum values, and performance optimization.

Main Takeaways

  1. Basic Usage of the MAX Function
    The MAX function is used to retrieve the maximum value of a specified column. It supports various data types, including numbers, strings, and dates.
  2. Conditional Maximum Retrieval
    By using the WHERE clause, you can retrieve maximum values that match specific conditions. This is useful for project-based or department-based analysis.
  3. Retrieving Maximum Values per Group
    We explained how to use the GROUP BY clause to retrieve maximum values for each group, such as salaries per department or sales per month.
  4. Retrieving Entire Records with the Maximum Value
    You learned how to efficiently retrieve full records containing maximum values using subqueries, JOINs, and window functions.
  5. Important Considerations When Using MAX
    It is important to consider NULL handling, multiple maximum values, and performance impact.
  6. FAQ
    We addressed common questions, including how to use MAX with multiple columns and tips for performance optimization.

Final Thoughts

By properly utilizing the MAX function, data analysis and reporting become much more efficient. Continue practicing SQL to build more advanced queries.

We hope this article helps deepen your understanding of data manipulation and analysis using MySQL.