SQL AGGREGATE FUNCTIONS – MAX
SELECT MAX(column1) FROM table_name WHERE condition;
Usually, the aggregate functions are used in conjunction with the GROUP BY/ HAVING clause, which gives even more meaningful results. The syntax for the query using MAX function using GROUP BY / HAVING clause is mentioned below –
SELECT column1, MAX(column2) FROM table_name WHERE condition1 GROUP BY column1 HAVING condition2;
At first, these might look little complicated, but once we go over few examples, it will make more sense.
Illustration – Consider the below employee table in the database which stores the information pertaining to employees in a company –
Query 1 – What is the maximum salary earned by any employee in ABC company?
SELECT MAX(salary) FROM employee;
Query 2 – What is the maximum salary earned by any employee in ABC company whose age is less than 35 years?
SELECT MAX(salary) FROM employee WHERE age<35;
Query 3 – What is the maximum salary earned by employees in ABC company by each department.
SELECT Department, MAX(salary) FROM employee GROUP BY Department;
Query 4 – What is the maximum salary earned by employees in ABC company by each department that gets less than 90000 as salary.
SELECT Department, MAX(salary) FROM employee GROUP BY Department HAVING MAX(salary) < 90000;