MySQL: MAX Function

  • Post author:
  • Post category:MySQL
  • Post comments:1 Comment
MySQL MAX Function

In this guide, we will explain how to use the MySQL MAX function with syntax and examples.

Description

The MySQL MAX function returns the maximum value of an expression.

Syntax

The syntax for the MAX function in MySQL is:

SELECT MAX(aggregate_expression)
FROM tables
[WHERE conditions];

OR the syntax for the MAX function when grouping the results by one or more columns is:

SELECT expression1, expression2, ... expression_n,
       MAX(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Parameters or Arguments

expression1, expression2, … expression_n

Expressions that are not encapsulated within the MAX function and must be included in the GROUP BY clause at the end of the SQL statement.

aggregate_expression

This is the column or expression from which the maximum value will be returned.

tables

The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.

WHERE conditions

Optional. These are conditions that must be met for the records to be selected.

Applies To

The MAX function can be used in the following versions of MySQL:

  • MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23

Example – With Single Expression

Let’s look at some MySQL MAX function examples and explore how to use the MAX function.

For example, you might wish to know how the maximum salary of all employees.

SELECT MAX(salary) AS "Highest Salary"
FROM employees;

In this MAX function example, we’ve aliased the MAX(salary) expression as “Highest Salary”. As a result, “Highest Salary” will display as the field name when the result set is returned.

Example – Using GROUP BY

In some cases, you will be required to use the GROUP BY clause with the MAX function.

For example, you could also use the MAX function to return the name of the department and the maximum salary in the department.

SELECT department, MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;

Because you have listed one column in your SELECT statement that is not encapsulated in the MAX function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

Next Topic : Click Here

This Post Has One Comment

Leave a Reply