SQL MIN() and MAX() Functions

SQL MIN() and MAX() Functions

SQL MIN() and MAX() Functions

In SQL, the MIN() and MAX() functions are used to retrieve the minimum and maximum values of a column in a table.

The MIN() function returns the smallest value of the selected column, while the MAX() function returns the largest value.

Here is the basic syntax for using the MIN() and MAX() functions:

				
					SELECT MIN(column_name)
FROM table_name
WHERE condition;

SELECT MAX(column_name)
FROM table_name
WHERE condition;
				
			

In these statements, column_name is the name of the column whose minimum or maximum value we want to retrieve, and table_name is the name of the table containing the column. The condition is an optional parameter that can be used to specify a filtering criterion for the rows in the table.

Let’s take a look at an example:

Suppose we have a table called sales that contains data about the sales made by a company. The table has three columns: id, product, and price. We want to retrieve the minimum and maximum prices of all the products sold.

				
					SELECT MIN(price) AS min_price, MAX(price) AS max_price
FROM sales; 

				
			

This query will return a result set with two columns: min_price and max_price, containing the minimum and maximum prices of all the products sold, respectively.

We can also use the WHERE clause to filter the results:

				
					SELECT MIN(price) AS min_price, MAX(price) AS max_price
FROM sales
WHERE product = 'Widget';

				
			

This query will return the minimum and maximum prices of the Widget product sold by the company.

The MIN() and MAX() functions can also be used in combination with other SQL functions, such as AVG(), SUM(), and COUNT(), to perform more complex queries on the data.

Join To Get Our Newsletter
Spread the love