MAX (Transact-SQL)

Returns the maximum value in a set of values.

Syntax

MAX ( [ALL | DISTINCT] expression ) [ OVER ( [ partition_by_clause ] order_by_clause ) ]

Parameters

Return Value

Returns the maximum value from the specified expression. The data type of the return value is the same as the data type of the expression.

Description

The MAX function is an aggregate function. It operates on a set of rows and returns a single value. It can be used in a SELECT statement to return the largest value of a specified column or expression across a group of rows.

When used with the OVER clause, MAX becomes a window function. This allows you to calculate the maximum value within a specified window (partition) of rows without collapsing the rows.

Examples

Example 1: Finding the highest salary in an employee table

SELECT MAX(Salary) AS HighestSalary
FROM Employees;

This query will return a single row with the highest salary from the Employees table.

Example 2: Finding the latest order date

SELECT MAX(OrderDate) AS LatestOrderDate
FROM Orders;

This query returns the most recent date from the OrderDate column in the Orders table.

Example 3: Using MAX with DISTINCT

SELECT MAX(DISTINCT UnitPrice) AS MaxUniquePrice
FROM Products;

This query finds the highest unique price among all products.

Example 4: Using MAX as a Window Function

SELECT
    EmployeeName,
    Salary,
    MAX(Salary) OVER (PARTITION BY Department) AS MaxSalaryInDepartment
FROM Employees;

This query returns each employee's name and salary, along with the maximum salary within their respective department. The original rows are preserved.

Considerations