Explain SQL MIN() and MAX() Functions
The SQL MIN()
and MAX()
functions are used to retrieve the minimum and maximum values from a set of data, respectively. They are aggregate functions, meaning they perform a calculation on a set of values and return a single value.
MIN() Function
The MIN()
function returns the smallest value in a set of values. Here's the syntax:
SELECT MIN(column_name) FROM table_name;
Example
Suppose we have a table named Employees
with the following data:
EmployeeID | Name | Salary |
---|---|---|
1 | Alice | 50000 |
2 | Bob | 60000 |
3 | Charlie | 55000 |
4 | David | 70000 |
5 | Eve | 45000 |
To find the minimum salary:
SELECT MIN(Salary) AS MinSalary FROM Employees;
Output
MinSalary |
---|
45000 |
MAX() Function
The MAX()
function returns the largest value in a set of values. Here's the syntax:
SELECT MAX(column_name) FROM table_name;
Example
Using the same Employees
table, to find the maximum salary:
SELECT MAX(Salary) AS MaxSalary FROM Employees;
Output
MaxSalary |
---|
70000 |
Using MIN() and MAX() with GROUP BY
You can also use MIN()
and MAX()
functions with the GROUP BY
clause to find the minimum and maximum values for each group of records.
Example
Suppose the Employees
table has an additional column Department
:
EmployeeID | Name | Salary | Department |
---|---|---|---|
1 | Alice | 50000 | HR |
2 | Bob | 60000 | IT |
3 | Charlie | 55000 | HR |
4 | David | 70000 | IT |
5 | Eve | 45000 | HR |
To find the minimum and maximum salary in each department:
SELECT Department, MIN(Salary) AS MinSalary, MAX(Salary) AS MaxSalary
FROM Employees
GROUP BY Department;
Output
Department | MinSalary | MaxSalary |
---|---|---|
HR | 45000 | 55000 |
IT | 60000 | 70000 |
These examples demonstrate how MIN()
and MAX()
functions can be used to extract the minimum and maximum values from a dataset in SQL.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.