The SQL MIN() and MAX() Functions
The SQL MIN() and MAX() functions in SQL are used to extract the minimum and maximum values from a given column in a database table.
To perform computations and get helpful information from your database, these functions are frequently used in conjunction with the SELECT query.
We will explain the SQL MIN() and MAX() functions with an example:
Examples of SQL MIN() and MAX() Functions
Example 1: Using the MIN() Function
SQL> SELECT MIN(Price) AS MinPrice
FROM Products;
MIN (Price) calculates the minimum value from the “Price” column.
AS MinPrice gives a name to the result column for clarity.
Example 2: Using the MAX Function
SQL> SELECT MAX(Price) AS MaxPrice
FROM Products;
MAX(Price) calculates the maximum value from the “Price” column.
AS MaxPrice provides a name for the result column.
Example 3: Using Aggregate Functions with Other Columns
You can also use the MIN and MAX functions in conjunction with other columns to find related information. For instance, if you want to find the product(s) with the minimum and maximum prices:
SQL> SELECT ProductName, Price FROM Products
WHERE Price = (SELECT MIN(Price) FROM Products)
OR Price = (SELECT MAX(Price) FROM Products);
Example 4: Using GROUP BY with MIN and MAX
You can use the GROUP BY clause with the MIN and MAX functions to find minimum and maximum values within groups.
SQL> SELECT Category, MIN(Price) AS MinPrice, MAX(Price) AS MaxPrice FROM Products
GROUP BY Category;
GROUP BY Category: groups the products by their categories.
MIN(Price) calculates: the minimum price for each category.
MAX(Price) calculates: the maximum price for each category.
These SQL MIN() and MAX() functions examples show how to locate the MIN and MAX values within a column or within groupings of data using SQL’s MIN and MAX procedures.
For various data analysis and reporting activities in database management, these capabilities are helpful.