Learn about SQL MAX() and MIN() with the help of examples. Learn how to use the SQL MAX() and MIN() functions to find the largest and smallest values in a column.
In SQL,
MAX()
function returns the maximum value of a column.MIN()
function returns the minimum value of a column.The syntax of the SQL MAX()
function is:
SELECT MAX(columnn)
FROM table;
Here,
column
is the name of the column you want to filtertable
is the name of the table to fetch the data fromFor example,
SELECT MAX(age)
FROM Customers;
Here, the SQL command returns the largest value from the age column.
Example: MAX() in SQL
The syntax of the SQL MIN()
function is:
SELECT MIN(columnn)
FROM table;
Here,
column
is the name of the column you want to filtertable
is the name of the table to fetch the data fromFor Example,
SELECT MIN(age)
FROM Customers;
Here, the SQL command returns the smallest value from the age column.
Example: MIN() in SQL
In the above examples, the field names in the result sets were MIN(age)
and MAX(age)
.
It is also possible to give custom names to these fields using the AS
keyword. For example,
-- use max_age as an alias for the maximum age
SELECT MAX(age) AS max_age
FROM Customers;
Here, the field name MAX(age)
is replaced with max_age in the result set.
Example: MAX() in SQL with Alias
The MAX()
and MIN()
functions also work with texts. For example,
--select the minimum value of first_name from Customers
SELECT MIN(first_name) AS min_first_name
FROM Customers;
Here, the SQL command selects the minimum value of first_name
based on the dictionary order.
Example: MIN() in SQL with String
As we know, the MAX()
function returns the maximum value. Similarly, the MIN()
function returns the minimum value.
However, if we want to select the whole row containing that value, we can use the nested SELECT
statement like this.
-- MIN() function in a nested SELECT statement
SELECT *
FROM Customers
WHERE age = (
SELECT MIN(age)
FROM Customers
);
Here, the SQL command selects all the customers with the smallest age.
Example: Nested MIN() in SQL
#sql