SQL Aggregates
SQL MIN and MAX
Finding Minimum and Maximum Values
MIN and MAX find the smallest and largest values, applicable to strings and numbers.
Introduction to MIN and MAX Functions
In SQL, the MIN and MAX functions are used to find the smallest and largest values in a set of data, respectively. These functions are versatile and can be applied to numerical data, strings, or even dates, making them powerful tools for data analysis and reporting.
Using MIN Function
The MIN function returns the smallest value from a set of values. This can be particularly useful when you want to find the lowest value in a column, such as the minimum price of all products in a database.
Using MAX Function
Similarly, the MAX function returns the largest value from a set of values. Use this function to find the highest value in a column, such as the maximum salary in an employee database.
MIN and MAX with Strings
When applied to string data, the MIN and MAX functions determine the smallest and largest values based on alphabetical order. For instance, you can use these functions to find the first and last names alphabetically in a list of students.
Working with Dates
SQL's MIN and MAX can also be used with date columns. These functions can help you determine the earliest and latest dates in a dataset, such as the oldest and newest order dates in a sales database.
Practical Examples and Use Cases
Here are some practical scenarios where MIN and MAX can be effectively used:
- Identifying the oldest employee in a company by birth date.
- Finding the lowest and highest grades in a class.
- Determining the earliest and latest start times for events.