Aggregate function MIN() in SQL
The MIN()
function in SQL is an aggregate function that returns the smallest value in a selected column. It is incredibly useful for data analysis, allowing you to quickly identify the minimum value in a dataset, which can be crucial for financial analysis, performance metrics, incident detection, etc.
Syntax
To use the MIN()
function, you simply need to include it in your SELECT
statement, specifying the column you want to analyze.
SELECT MIN(column_name)
FROM table_name
For instance, to find the lowest price from a products table, your query would look like this:
SELECT MIN(price)
FROM products
In this query,
MIN()
looks like any scalar function (think pure math function that accepts a bunch of arguments and returns a value as a result), but itβs actually acting on an aggregation β the entire table is our group.
Using MIN() in complex queries
Most of the time, youβll use the MIN()
function with the GROUP BY
statement to find the minimum values within each group.
SELECT
country,
MIN(age)
FROM users
GROUP BY country
This query returns the lowest age for each user country. The same way we can aggregate revenue of marketing campaigns, revenue of countries, usage per app feature, etc.
Finding the oldest record
Another great application of the MIN()
function is looking up the oldest value in a table. That helps when weβre exploring a new database and want to make sense of our data.
Hereβs a query that finds the signup timestamp of the very first user:
SELECT MIN(created_at)
FROM users
The MIN()
function is a straightforward yet powerful tool in SQL, itβs simply a must-have in your Data Analysis repertoire.
Database compatibility
MySQL
|
PostgreSQL
|
SQLite
|
Redshift
|
Big Query
|
Snowflake
|
|
---|---|---|---|---|---|---|
MIN |
|
|
|
|
|
|
MIN