Tutorialsteacher

Follow Us

SQL MAX() function

The MAX() function is an aggregate function that is used to find the largest value in the given column or expression. It can be applied on the numeric, character, or date values.

Syntax:

SELECT MAX(column_name) FROM table_name [WHERE condition] [GROUP BY];

For the demo purpose, we will use the following Employee and Department tables in all examples.

EmpIdFirstNameLastNameEmailSalaryDeptId
1JohnKing'[email protected]'2400010
2JamesBond6000020
3NeenaKochhar'[email protected]'1500020
4LexDe Haan'[email protected]'900030
5AmitPatel6000030
6AbdulKalam'[email protected]'480040

The following selects the maximum salary from the Employee table.

SQL Script: MAX()
SELECT MAX(Salary) AS "Highest Salary" FROM Employees;
Highest Salary
60000

The following query gets all employees whose salary is maximum.

SQL Script: MAX()
SELECT * FROM Employee WHERE Salary = (SELECT MAX(Salary) FROM Employee);
EmpIdFirstNameLastNameEmailSalaryDeptId
5AmitPatel6000030
2JamesBond6000020

The MAX() is an aggregate function, so it can be used in Group By queries. The following query gets highest salary in each department.

SQL Script: MAX() with Group By
SELECT DeptId, MAX(Salary) AS "Highest Salary" FROM Employee GROUP BY DeptId;
DeptIdHighest Salary
1024000
2060000
3060000
404800

The MAX() function can be allpied on the varchar columns. The following selects the largest FirstName from the Employee table.

SQL Script: MAX() with varchar column
SELECT MAX(FirstName) AS "Largest FirstName" FROM Employee;
Largest FirstName
James