SQL MIN() and MAX()

The SQL MIN() and MAX() Functions

The MIN() and MAX() functions are aggregate functions used to find the minimum and maximum values in a set of values, respectively.


MIN() Function

The MIN() function returns the smallest value of the selected column.

MIN() Syntax

SELECT MIN(column_name)
FROM table_name
WHERE condition;

MAX() Function

The MAX() function returns the largest value of the selected column.

MAX() Syntax

SELECT MAX(column_name)
FROM table_name
WHERE condition;

Demo Database

Below is a selection from the Orders table:

Orders Table:

OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

Example 1: Using MIN()

The following SQL statement finds the smallest CustomerID in the Orders table.

MIN() Example

SELECT MIN(CustomerID) AS SmallestCustomerID
FROM Orders;

Example 2: Using MAX()

The following SQL statement finds the largest CustomerID in the Orders table.

MAX() Example

SELECT MAX(CustomerID) AS LargestCustomerID
FROM Orders;

Note: The AS keyword is used to create an alias for the column, making the result set more readable. We will cover aliases in a later chapter.