MAX Function - SQL


Overview


The MAX function in SQL returns the highest value in a specified column, helping to identify the maximum value within a dataset. It is often used in SELECT statements to find the largest value from a set of rows, optionally filtered by a condition.

Example:

SELECT MAX(salary)
FROM company.employees
WHERE department_id = 1

Syntax:

SELECT MAX(column_name)
FROM table_name
[WHERE condition]

This returns the highest value in column_name from table_name that meets the specified condition. In this syntax, the WHERE Statement is optional; if omitted, the MAX function will return the highest value from all rows in the table.

Sample Data:

department_id salary
3 123000
2 135000
3 115000
NULL 115000
2 125000
1 120000
1 105000
5 200000
2 107000
1 100000

Example: Without the WHERE Statement


In this example, we are returning the highest salary value in the company.employees table. The final output is 200000, which means that the highest salary in the company is 200000.


Example: With the WHERE Statement


In this example, we are returning the highest salary value in the company.employees table where the department_id column equals 1. The final output is 120000, which means that the highest salary in department_id 1 is 200000.