SQL min
Created By: chatGPT
The SQL MIN() function is used to return the smallest value from a specified column in a database table. This is particularly useful when working with aggregated data or seeking to find the minimum entry in a dataset. The function can be employed with various data types, such as
NUMERIC
, DATE
, or CHAR
. Below, you'll find some examples demonstrating how to use the MIN() function in SQL.SELECT MIN(column_name) AS min_value
FROM table_name;
You can also apply the MIN() function with the GROUP BY clause to find the minimum value for each group. Here's how that can be done.
SELECT group_column, MIN(value_column) AS min_value
FROM table_name
GROUP BY group_column;
In case you wish to filter records and find the minimum value under certain conditions, you can use the WHERE clause. This example illustrates that concept.
SELECT MIN(column_name) AS min_value
FROM table_name
WHERE condition;
To utilize the MIN() function correctly, ensure that the column specified holds compatible data types. Using MIN() on an incompatible type will return an error or an unexpected result.
SELECT MIN(price) AS lowest_price
FROM products;
Let's say you want to find the earliest date in a column of dates from an orders table. You would write a query like this:
SELECT MIN(order_date) AS earliest_order_date
FROM orders;