PostgreSQL MAKE_INTERVAL() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL MAKE_INTERVAL()
function to create an interval from the interval’s components
Introduction to the PostgreSQL MAKE_INTERVAL() function
The MAKE_INTERVAL()
function allows you to create an interval from years, months, weeks, days, hours, minutes, and seconds.
Here’s the syntax of the MAKE_INTERVAL()
function:
In this syntax:
years
is an integer representing the number of years.months
is an integer representing the number of months.weeks
is an integer representing the number of weeks.days
is an integer representing the number of days.hours
is an integer representing the number of hours.mins
is an integer representing the number of minutes.secs
is a double-precision number representing the number of seconds.
All of these parameters are optional and default to zero.
The MAKE_INTERVAL()
function returns a value of interval type.
Besides the MAKE_INTERVAL()
function, you can use the INTERVAL
literal syntax to create an interval:
The INTERVAL
literal syntax allows you to create an interval by specifying all components in a single string. It is suitable for creating static or predefined intervals.
On the other hand, the MAKE_INTERVAL()
function offers the flexibility to specify each component separately and is ideal for creating an interval dynamically. For example, you can use the MAKE_INTERVAL()
function to create an interval from values stored in a table.
PostgreSQL MAKE_INTERVAL() function examples
Let’s explore some examples of using the MAKE_INTERVAL()
function.
1) Basic MAKE_INTERVAL() function example
The following example uses the MAKE_INTERVAL()
function to create an interval that represents 1 year, 2 months, 3 days, and 4 hours:
Output:
2) Using the MAKE_INTERVAL() function with default values
All of the parameters of the MAKE_INTERVAL()
function are optional and default to zero. For example, the following statement creates an interval zero:
Output:
3) Using the MAKE_INTERVAL( ) function with table data
First, create a new table called time_data
:
Second, insert some rows into the time_data table:
Output:
Third, use the MAKE_INTERVAL()
function to create intervals from the data stored in the time_data
table:
Output:
Summary
- Use the
MAKE_INTERVAL()
function to construct an interval from the provided components, such as years, months, days, hours, minutes, and seconds.