SQL MIN
Tutorial
The MIN
command is used to find the minimum value in a given result set. It is frequently used with the GROUP BY
command.
Example 1 (no aggregation)
-- Works in PostgreSQL, MySQL, SQL Server, and Oracle
SELECT
MIN(dollar_amount) as lowest_payment
FROM
rent_payments;
rent_payments
table
id | tenant_id | payment_date | dollar_amount |
---|---|---|---|
1 | 1 | 3/1/2018 | 2000 |
2 | 2 | 3/2/2018 | 1500 |
3 | 3 | 3/1/2018 | 1800 |
4 | 4 | 3/3/2018 | 1900 |
5 | 1 | 4/2/2018 | 2000 |
6 | 4 | 4/2/2018 | 1900 |
Query results
lowest_payment |
---|
1500 |
Example 2 (with aggregation)
-- Works in PostgreSQL, MySQL, SQL Server, and Oracle
SELECT
payment_date,
MIN(dollar_amount) as lowest_payment
FROM
rent_payments
GROUP BY
payment_date;
rent_payments
table
id | tenant_id | payment_date | dollar_amount |
---|---|---|---|
1 | 1 | 3/1/2018 | 2000 |
2 | 2 | 3/2/2018 | 1500 |
3 | 3 | 3/1/2018 | 1800 |
4 | 4 | 3/3/2018 | 1900 |
5 | 1 | 4/2/2018 | 2000 |
6 | 4 | 4/2/2018 | 1900 |
Query results
payment_date | lowest_payment |
---|---|
3/1/2018 | 1800 |
3/2/2018 | 1500 |
3/3/2018 | 1900 |
4/2/2018 | 1900 |
Explanation
We are finding the minimum value of dollar_amount
for each unique value of the payment_date
column.