Geek Slack

Getting Started with SQL Server
About Lesson


SQL MIN() and MAX() Functions


SQL MIN() and MAX() Functions

SQL MIN() and MAX() functions are used to find the smallest and largest values in a specified column, respectively.

MIN() Function

The MIN() function returns the smallest value in a set of values.

SELECT MIN(salary) AS lowest_salary FROM employees;

This query finds the lowest salary among all employees.

MAX() Function

The MAX() function returns the largest value in a set of values.

SELECT MAX(salary) AS highest_salary FROM employees;

This query finds the highest salary among all employees.

Using MIN() and MAX() with GROUP BY

Both MIN() and MAX() can be used with the GROUP BY clause to find the minimum and maximum values for each group of results.

SELECT department, MIN(salary) AS lowest_salary, MAX(salary) AS highest_salary
FROM employees
GROUP BY department;

This query finds the lowest and highest salaries in each department.

Example 1: Using MIN() with a WHERE Clause

SELECT MIN(salary) AS lowest_salary
FROM employees
WHERE department = 'Sales';

This query finds the lowest salary in the Sales department.

Example 2: Using MAX() with a WHERE Clause

SELECT MAX(salary) AS highest_salary
FROM employees
WHERE department = 'Marketing';

This query finds the highest salary in the Marketing department.

Example 3: Combining MIN() and MAX()

SELECT MIN(age) AS youngest_employee, MAX(age) AS oldest_employee
FROM employees;

This query finds the youngest and oldest employees in the company.

Example 4: MIN() and MAX() with Date Columns

SELECT MIN(hire_date) AS earliest_hire_date, MAX(hire_date) AS latest_hire_date
FROM employees;

This query finds the earliest and latest hire dates among all employees.

The MIN() and MAX() functions are very useful for finding the extremes in your data, whether you’re dealing with numbers, dates, or other types of comparable values.

Join the conversation