SQL MIN
What is SQL MIN?
The SQL MIN function is an aggregate function used to retrieve the minimum (lowest) value from a specified column in a database table. It allows you to find the smallest value within a column, which is particularly useful for identifying the minimum value in numerical or date-related data.
When you would use it
You would use the SQL MIN function when you need to determine the smallest value in a specific column. This can be valuable in various scenarios, such as finding the earliest date, the lowest price, or the minimum value of any numeric field in your data.
Syntax
The syntax for using the MIN function is as follows:
SELECT MIN(column_name) FROM table_name WHERE condition;
column_name
: The name of the column for which you want to find the minimum value.table_name
: The name of the table containing the data.condition
(optional): An optional condition to filter the rows for which you want to find the minimum.
Parameter values
column_name
: The name of the column in the specified table for which you want to determine the minimum value.table_name
: The name of the table where the data is stored.condition
(optional): A condition that filters the rows if you want to apply additional filtering before finding the minimum.
Example query
Suppose we have a table named "product_prices" with columns "product_id" and "price." We want to find the minimum price among all products:
SELECT MIN(price)
FROM product_prices
-- Comment the line below to show it doesn't affect the query.
-- WHERE category = 'Electronics';
In the above query, we use the MIN function to find the minimum price among all products in the "product_prices" table.
Example table response
Assuming the "product_prices" table contains the following data:
| product_id | price |
|------------|-------- |
| 1 | 99.99 |
| 2 | 149.95 |
| 3 | 79.99 |
| 4 | 199.99 |
The query mentioned earlier would return the following result:
| MIN(price) |
|------------ |
| 79.99 |
This represents the minimum price among all products in the "product_prices" table.
Use cases
- Finding the lowest price for a product.
- Identifying the earliest date in a dataset.
- Determining the minimum value within a numeric column, such as the minimum score in a test result table.
SQL languages this is available for
The SQL MIN function is a standard SQL feature and is available in most relational database management systems (RDBMS) that support SQL. This includes popular RDBMS like MySQL, PostgreSQL, Oracle, SQL Server, and SQLite. The specific syntax and behavior may vary slightly between database systems, but the fundamental functionality remains the same.