You are currently viewing SQL 1.15 SQL MIN() and MAX()

SQL 1.15 SQL MIN() and MAX()

Absolutely! Let’s dive into learning the basics of using SQL’s MIN() and MAX() functions. SQL, or Structured Query Language, is a powerful tool for managing and manipulating data in relational databases. The MIN() and MAX() functions are used to find the minimum and maximum values respectively from a set of values within a specified column. Here’s a step-by-step tutorial along with sample code snippets:

1. Basic Syntax:

The basic syntax for using MIN() and MAX() functions is as follows:

SELECT MIN(column_name) AS min_value
FROM table_name;

SELECT MAX(column_name) AS max_value
FROM table_name;

Here, column_name is the name of the column from which you want to find the minimum or maximum value, and table_name is the name of the table containing that column.

2. Example Dataset:

For demonstration purposes, let’s consider a simple table named students with the following structure:

student_idnameagegrade
1Alice20A
2Bob22B
3Charlie21A
4David19C
5Emily20B

3. Finding the Minimum Value:

Let’s start by finding the minimum age from the students table:

SELECT MIN(age) AS min_age
FROM students;

Explanation:

  • MIN(age) retrieves the minimum value from the age column.
  • AS min_age aliases the result column as min_age for better readability.

4. Finding the Maximum Value:

Next, let’s find the maximum age from the students table:

SELECT MAX(age) AS max_age
FROM students;

Explanation:

  • MAX(age) retrieves the maximum value from the age column.
  • AS max_age aliases the result column as max_age.

5. Output:

  • For the MIN(age) query, the result will be:
min_age
-------
19
  • For the MAX(age) query, the result will be:
max_age
-------
22

6. Additional Example:

Let’s find the minimum and maximum grades from the students table:

SELECT MIN(grade) AS min_grade,
       MAX(grade) AS max_grade
FROM students;

Explanation:

  • MIN(grade) retrieves the minimum value from the grade column.
  • MAX(grade) retrieves the maximum value from the grade column.

7. Output:

  • For the additional example, the result will be:
min_grade | max_grade
----------|----------
A         | C

Here, it shows that the minimum grade is ‘A’ and the maximum grade is ‘C’.

Conclusion:

That’s it! You’ve learned how to use the MIN() and MAX() functions in SQL to find the minimum and maximum values within a dataset. These functions are extremely useful for analyzing and summarizing data in relational databases. Practice with different datasets to reinforce your understanding.

Leave a Reply