MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The MIN()
function in MySQL is an aggregate function that returns the minimum value in a set of values. You can use the MIN()
function to select the lowest (minimum) value in a column.
Syntax:
SELECT MIN(column_name) FROM table_name WHERE condition;
Example:
Consider we have a table named products
, which contains the following data:
ProductID | ProductName | Price |
---|---|---|
1 | Apple | 1.2 |
2 | Banana | 0.8 |
3 | Orange | 1 |
4 | Kiwi | 1.5 |
5 | Mango | 1.3 |
If we want to find the product with the lowest price, we can use the MIN()
function like this:
SELECT MIN(Price) AS MinPrice FROM products;
The MinPrice
after AS
is an alias which will be used as the column name for the result set.
This will return:
MinPrice |
---|
0.8 |
Using MIN()
in a column with text data:
You can use the MIN()
function on a column containing text data to get the minimum value according to the column's collation.
For example, if you want to find the product that is first in alphabetical order, you could use the MIN()
function like this:
SELECT MIN(ProductName) AS FirstProduct FROM products;
This will return:
FirstProduct |
---|
Apple |
Using MIN()
with GROUP BY
:
You can use the MIN()
function in conjunction with the GROUP BY
clause to get the minimum value for each group.
For example, consider we have another table orders
:
OrderID | ProductID | Quantity |
---|---|---|
1 | 1 | 5 |
2 | 2 | 10 |
3 | 1 | 3 |
4 | 3 | 7 |
5 | 2 | 2 |
If you want to find the minimum quantity ordered of each product, you could do this:
SELECT ProductID, MIN(Quantity) AS MinQuantity FROM orders GROUP BY ProductID;
This will return:
ProductID | MinQuantity |
---|---|
1 | 3 |
2 | 2 |
3 | 7 |
This shows the minimum quantity ordered for each product in the orders
table.
MySQL MIN Function Example:
SELECT MIN(column_name) AS min_value FROM table_name;
How to Use MIN Function in MySQL:
SELECT MIN(price) AS min_price FROM products;
Finding the Minimum Value with MIN in MySQL:
SELECT MIN(salary) AS lowest_salary FROM employees;
Grouping and MIN Function in MySQL:
SELECT department_id, MIN(salary) AS min_salary FROM employees GROUP BY department_id;
MIN Function with WHERE Clause in MySQL:
SELECT MIN(total_amount) AS min_order_amount FROM orders WHERE status = 'Shipped';
Using MIN Function for Date and Time Values in MySQL:
SELECT MIN(order_date) AS earliest_order_date FROM orders;
Handling NULL Values with MIN Function in MySQL:
SELECT MIN(IFNULL(salary, 0)) AS min_salary FROM employees;
Examples of Using MIN Function in MySQL Queries:
SELECT MIN(stock_quantity) AS min_stock FROM products;
SELECT department_id, MIN(hire_date) AS earliest_hire_date FROM employees GROUP BY department_id;