In this post explains how to use the MAX function in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server (Transact-SQL), the MAX function returns the maximum value of an expression.
The syntax for the MAX function in SQL Server (Transact-SQL) is:
OR the syntax for the MAX function when grouping the results by one or more columns is:
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.
This is the column or expression from which the maximum value will be returned.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. These are conditions that must be met for the records to be selected.
The MAX function can be used in the following versions of SQL Server (Transact-SQL):
Let's look at some SQL Server MAX function examples and explore how to use the MAX function in SQL Server (Transact-SQL).
For example, you might wish to know how the maximum quantity of all products.
In this MAX function example, we've aliased the MAX(quantity) expression as "Highest Quantity". As a result, "Highest Quantity" will display as the field name when the result set is returned.
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.
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.