MIN and MAX in SQL

In SQL, determining the minimum and maximum values within a dataset is a fundamental requirement in many applications. Whether you are calculating the smallest or largest values in a column, such as the lowest salary in a company or the highest price of products, SQL provides two simple yet powerful aggregate functions: MIN() and MAX().

In this chapter, we will explore these functions, their syntax, use cases, and advanced scenarios. We will also dive into how MIN() and MAX() can be used alongside other SQL features such as GROUP BY, HAVING, and subqueries.

Basic Syntax of MIN() and MAX() in SQL

The MIN() and MAX() functions return the smallest and largest values, respectively, from a column of data. Both functions are aggregate functions, which means they operate on a set of values to return a single result.

  • MIN(): Returns the smallest value.
  • MAX(): Returns the largest value.

The basic syntax is:

				
					SELECT MIN(column_name), MAX(column_name)
FROM table_name
WHERE condition;

				
			

Using MIN() and MAX() for Simple Queries

Example 1: Finding the Minimum and Maximum Salary

Consider an employees table:

IDNameDepartmentSalary
1John DoeHR5000
2Jane SmithIT6000
3David GreenSales7000
4Sarah BrownIT8000
5James WhiteSales5500

To find the minimum and maximum salary in the employees table:

Query:

				
					SELECT MIN(salary) AS MinSalary, MAX(salary) AS MaxSalary
FROM employees;

				
			

Output:

MinSalaryMaxSalary
50008000

Using MIN() and MAX() with WHERE Clause

You can combine MIN() and MAX() with the WHERE clause to filter the data before calculating the minimum or maximum values.

Example 2: Finding Minimum and Maximum Salary in the IT Department

To find the minimum and maximum salary of employees in the IT department:

Query:

				
					SELECT MIN(salary) AS MinITSalary, MAX(salary) AS MaxITSalary
FROM employees
WHERE department = 'IT';
;

				
			

Output:

MinITSalaryMaxITSalary
60008000

The query filters employees from the IT department and returns the smallest and largest salary values from that filtered set.

Using MIN() and MAX() with GROUP BY

The GROUP BY clause is often used alongside MIN() and MAX() to calculate the minimum or maximum values for each group of data, such as each department or category.

Example 3: Finding Minimum and Maximum Salary by Department

If you want to find the minimum and maximum salary for each department:

Query:

				
					SELECT department, MIN(salary) AS MinSalary, MAX(salary) AS MaxSalary
FROM employees
GROUP BY department;

				
			

Output:

DepartmentMinSalaryMaxSalary
HR50005000
IT60008000
Sales55007000

The query groups the employees by department and returns the minimum and maximum salary for each department.

Using MIN() and MAX() with HAVING Clause

The HAVING clause is used to filter the result of aggregate functions, such as MIN() and MAX(), after they are applied. This is especially useful when you want to find groups that meet certain criteria.

Example 4: Departments Where the Maximum Salary is Greater Than 6000

To find departments where the maximum salary exceeds 6000:

Query:

				
					SELECT department, MAX(salary) AS MaxSalary
FROM employees
GROUP BY department
HAVING MAX(salary) > 6000;

				
			

Output:

DepartmentMaxSalary
IT8000
Sales7000

The query first calculates the maximum salary for each department and then filters the results to show only those departments where the maximum salary is greater than 6000.

Using MIN() and MAX() with Multiple Columns

You can use MIN() and MAX() on more than one column in a single query. This is useful for analyzing multiple aspects of your data simultaneously.

Example 5: Finding Minimum and Maximum Salary and ID

To find the minimum salary and the minimum id value from the employees table:

Query:

				
					SELECT MIN(salary) AS MinSalary, MIN(id) AS MinID, MAX(salary) AS MaxSalary, MAX(id) AS MaxID
FROM employees;

				
			

Output:

MinSalaryMinIDMaxSalaryMaxID
5000180005

The query returns both the minimum and maximum salary, as well as the minimum and maximum id values from the employees table.

Using Subqueries with MIN() and MAX()

In more complex scenarios, you may need to use MIN() and MAX() within subqueries to filter records or perform calculations.

Example 6: Finding Employee with Maximum Salary

To find the name of the employee with the highest salary:

Query:

				
					SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

				
			

Output:

NameSalary
Sarah Brown8000

The subquery retrieves the maximum salary, and the outer query fetches the employee(s) who earn this salary.

Using MIN() and MAX() with Date and Time Columns

MIN() and MAX() can also be used with date and time columns, which is useful for finding the earliest or latest events in a dataset.

Example 7: Finding the Earliest and Latest Hire Dates

Consider a hire_date column in the employees table:

IDNameHire Date
1John Doe2020-05-01
2Jane Smith2019-08-15
3David Green2021-01-10
4Sarah Brown2019-12-22

To find the earliest and latest hire dates:

Query:

				
					SELECT MIN(hire_date) AS EarliestHireDate, MAX(hire_date) AS LatestHireDate
FROM employees;

				
			

Output:

EarliestHireDateLatestHireDate
2019-08-152021-01-10

The query returns the earliest and latest hire dates from the employees table.

Combining MIN() and MAX() with Other Aggregate Functions

You can combine MIN() and MAX() with other aggregate functions like SUM(), COUNT(), and AVG() to perform more comprehensive data analysis.

Example 8: Combining MIN(), MAX(), and AVG()

To find the minimum, maximum, and average salary in the employees table:

Query:

				
					SELECT MIN(salary) AS MinSalary, MAX(salary) AS MaxSalary, AVG(salary) AS AvgSalary
FROM employees;

				
			

Output:

MinSalaryMaxSalaryAvgSalary
500080006300

This query returns the minimum, maximum, and average salary values in one go, providing a broader picture of the salary distribution.

Performance Considerations

When using MIN() and MAX() on large datasets, performance can become a concern, especially if the columns being analyzed are not indexed. Here are some tips to optimize queries involving MIN() and MAX():

  • Index the Columns: If you’re frequently querying the minimum or maximum values of a column, ensure that column is indexed. This significantly speeds up the query.
  • Use Partitioning: For very large datasets, partitioning the table based on a logical criterion (e.g., date ranges) can improve performance.
  • Avoid Unnecessary Grouping: If you don’t need to group data, avoid using GROUP BY as it adds extra overhead to the query execution.

The MIN() and MAX() functions are essential tools for extracting the smallest and largest values from datasets in SQL. From simple queries to more complex scenarios involving GROUP BY, HAVING, and subqueries, these functions provide flexibility in data analysis.Understanding how to use MIN() and MAX() effectively, along with considering performance optimizations, ensures that you can retrieve the most critical information from your data efficiently. Happy coding !❤️

Table of Contents