This SQL tutorial explains how to use the SQL MAX function with syntax and examples.
DESCRIPTION
The SQL MAX function is used to return the maximum value of an expression in a SELECT statement.
SYNTAX
The syntax for the SQL MAX function 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.
EXAMPLE - WITH SINGLE EXPRESSION
The simplest way to use the SQL MAX function would be to return a single field that calculates the MAX value.
For example, you might wish to know the maximum salary of all employees.
SELECT MAX(salary) AS "Highest salary" FROM employees;
In this SQL MAX function example, we've aliased the MAX(salary) field as "Highest salary". As a result, "Highest salary" will display as the field name when the result set is returned.
EXAMPLE - USING SQL GROUP BY CLAUSE
In some cases, you will be required to use the SQL GROUP BY clause with the SQL MAX function.
For example, you could also use the SQL MAX function to return the name of each 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 SQL SELECT statement that is not encapsulated in the MAX function, you must use the SQL GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.
No comments:
Post a Comment