Open In App

SQL MIN() and MAX()

The Min() function is used to return the minimum value of the selected columns, and The Max() function is used to return the maximum value of the selected columns.

In this article, we will look for several functionalities depending on min and max functions.



SQL MIN() Function

SQL min function returns the smallest value in the column. The MIN() function provides the smallest value of the chosen column. similarly, the max function will return the max value from the records. 

Syntax 



SELECT MIN(column_name)

FROM table_name

WHERE condition;

Parameter Explanation

SQL MAX() Functions 

SQL max function returns the largest value in the column. The MAX() function provides the largest value of the chosen column. SQL max functions return the largest value in the column.

The MAX() function provides the largest value of the chosen column. similarly, the min function will return the min value from the records. In this article, we will already see MIN and now we will look into  MAX functions in SQL.

Syntax

SELECT MAX(column_name)

FROM table_name

WHERE condition;

Let’s assume that we have one table with the name”emp” and we have to fetch the person with min age.

SQL CREATE Table:

CREATE TABLE Customer(
    CustomerID INT PRIMARY KEY,
    CustomerName VARCHAR(50),
    LastName VARCHAR(50),
    Country VARCHAR(50),
    Age int(2),
  Phone int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
       (2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
       (3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
       (4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
       (5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');

Output:

 

Query:

SELECT MIN(Age) FROM Customer ;

Output:

 

 The following SQL statement finds the highest Age:

Query:

SELECT Max(Age) FROM Customer;

Output:

 

Using MIN() and MAX() with Other Columns

Suppose we want to fetch a person’s name with min age as column min_age then we can use the following query.

Query:

SELECT CustomerName,
  MIN(Age) AS min_age 
FROM Customer;

Output:

 

Using MIN() or MAX() In the HAVING  Clause

Suppose we want to fetch a person’s name with max age as column max_age then we can use the following query but with some conditions like min age at least 22Query:

SELECT CustomerName,
  MAX(Age) AS max_age 
FROM Customer
HAVING MIN(Age)>22;

Output:

 

Conclusion

The SQL aggregate functions MIN() and MAX() are widely used. Here we described various applications for them in this article. The primary distinction between them is that while MAX() returns the maximum value, MIN() locates the minimum value among a set of values.

Article Tags :
SQL