MAX(): Find the Largest Value

The MAX() function returns the largest value in a column.
It works with numbers, dates and text (text is compared in alphabetical order).


Syntax

SELECT MAX(column) FROM table_name WHERE condition;

Example 1: Maximum Age of All Employees

SELECT MAX(age) FROM employees;

Output:

 max 
-----
  33
(1 row)

This returns the oldest age of any employee.


Example 2: Maximum Age per Department

SELECT department, MAX(age) AS oldest
FROM employees
GROUP BY department
ORDER BY department;

Output:

 department | oldest 
------------+--------
 Finance    |     33
 HR         |     28
 IT         |     33
 Marketing  |     30
 Sales      |     31
(5 rows)

This returns the oldest age in each department.


Example 3: Last Name Alphabetically

SELECT MAX(name) FROM employees;

Output:

 max  
------
 Tina
(1 row)

For text, the largest value is the one that comes last in alphabetical order.


Tip

  • MAX() ignores NULL values.
  • It works with numbers, text and dates.

In the exercise, find the oldest age in one department.