PostgreSQL MIN() Function
Summary: in this tutorial, you will learn how to use PostgreSQLMIN()
function to get the minimum value of a set.
Introduction to PostgreSQL MIN function
PostgreSQL MIN()
function is an aggregate function that returns the minimum value in a set of values.
To find the minimum value in a column of a table, you pass the column name the MIN()
function. The data type of the column can be numeric, string, or any comparable type.
Here’s the basic syntax of the MIN()
function:
Unlike the AVG()
, COUNT()
and SUM()
functions, the DISTINCT
option does not have any effects on the MIN()
function.
PostgreSQL MIN() function examples
We will use the film
, film_category
, and category
tables from the dvdrental sample database for demonstration.
1) Basic PostgreSQL MIN() function example
The following example uses the MIN()
function to get the lowest rental rate from the rental_rate
column the film
table:
Output:
The query returns 0.99, which is the lowest rental rate.
2) Using the PostgreSQL MIN() function in a subquery example
The following example uses the MIN()
function in a subquery to get the film information of the film with the lowest rental rate:
Output:
How it works.
- First, the subquery to select the lowest rental rate.
- Then, the outer query selects films with rental rates equal to the lowest rental rate returned by the subquery.
3) Using PostgreSQL MIN() function with GROUP BY clause example
In practice, you often use the MIN
function with the GROUP BY
clause to find the lowest value in each group.
The following statement uses the MIN()
function with the GROUP BY
clause to find the lowest replacement cost of films by category:
Output:
4) Using PostgreSQL MIN() function with the HAVING clause example
It’s possible to use the MIN
function in the HAVING
clause the filter of the groups whose minimum values meet a specific condition.
The following query uses the MIN()
function to find the lowest replacement costs of films grouped by category, selecting only groups with replacement costs greater than 9.99
:
Output:
5) Using the PostgreSQL MIN() function with other aggregate functions example
It’s possible to use the MIN()
function with other aggregate functions such as MAX()
function in the same query.
The following example uses the MIN()
and MAX()
function to find the shortest and longest films by category:
Output:
Summary
- Use the
MIN()
function to find the lowest value in a set of values. - Use the
MIN()
withGROUP BY
clause to find the lowest value in a group of values.