Geek Slack

My SQL Tutorial
About Lesson



MySQL MIN() and MAX() Functions


MySQL MIN() and MAX() Functions

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

Basic Syntax:

MIN() Function Syntax

SELECT MIN(column_name)
FROM table_name;

This SQL command selects the minimum value from column_name in table_name.

MAX() Function Syntax

SELECT MAX(column_name)
FROM table_name;

This SQL command selects the maximum value from column_name in table_name.

Examples Using MIN() and MAX():

Example: MIN() Function

SELECT MIN(price)
FROM products;

This SQL command selects the minimum value from the price column in the products table.

Example: MAX() Function

SELECT MAX(price)
FROM products;

This SQL command selects the maximum value from the price column in the products table.

Using MIN() and MAX() with WHERE Clause:

Example: MIN() with WHERE

SELECT MIN(price)
FROM products
WHERE category = 'Electronics';

This SQL command selects the minimum value from the price column in the products table where the category is ‘Electronics’.

Example: MAX() with WHERE

SELECT MAX(price)
FROM products
WHERE category = 'Electronics';

This SQL command selects the maximum value from the price column in the products table where the category is ‘Electronics’.

Using MIN() and MAX() with GROUP BY Clause:

Example: MIN() with GROUP BY

SELECT category, MIN(price)
FROM products
GROUP BY category;

This SQL command selects the minimum value from the price column in the products table for each category.

Example: MAX() with GROUP BY

SELECT category, MAX(price)
FROM products
GROUP BY category;

This SQL command selects the maximum value from the price column in the products table for each category.

Conclusion

The MIN() and MAX() functions in MySQL are useful for finding the smallest and largest values in a column, respectively. They can be used with other SQL clauses like WHERE and GROUP BY to refine and group results.

Join the conversation