PostgreSQL Tutorial

  • Home
  • Stored Procedures
  • Triggers
  • Views
  • Interfaces
    • PostgreSQL PHP
    • PostgreSQL Python
    • PostgreSQL JDBC
  • Functions
Home / PostgreSQL Tutorial / A Comprehensive Look at PostgreSQL Interval Data Type

A Comprehensive Look at PostgreSQL Interval Data Type

Summary: in this tutorial, you will learn about the PostgreSQL interval data type and how to manipulate interval values.

Introduction to PostgreSQL interval data type

The interval data type allows you to store and manipulate a period of time in years, months, days, hours, minutes, seconds, etc. The following illustrates the interval type:

1
@ interval [ fields ] [ (p) ]  

An interval value requires 16 bytes storage size that can store a period with the allowed range is from -178,000,000 years to 178,000,000 years.

In addition, an interval value can have an optional precision value p with the permitted range is from 0 to 6. The precision p is the number of fraction digits retained in the second fields.

The at sign ( @) is optional therefore you can omit it.

The following  examples show some interval values:

1
2
interval '2 months ago';
interval '3 hours 20 minutes';

Internally, PostgreSQL stores interval values as months, days, and seconds. The months and days values are integers while the seconds can field can have fractions.

The interval values are very useful when doing date or time arithmetic. For example, if you want to know the time of 3 hours 2 minutes ago at the current time of last year, you can use the following statement:

1
2
3
4
SELECT
now(),
now() - INTERVAL '1 year 3 hours 20 minutes'
             AS "3 hours 20 minutes ago of last year";

PostgreSQL Interval Example

Let’s see how to format interval values for input and output.

PostgreSQL interval input format

PostgreSQL provides you with the following verbose syntax to write the interval values:

1
quantity unit [quantity unit...] [direction]

  • quantity is a number, sign + or - is also accepted
  • unit can be any of millennium, century, decade, year, month, week, day, hour, minute, second, millisecond, microsecond, or abbreviation (y, m, d, etc.,) or plural forms (months, days, etc.).
  • direction can be ago or empty string ''

This format is called postgres_verbose which is also used for the interval output format. The following examples illustrate some interval values that use the verbose syntax:

1
2
INTERVAL '1 year 2 months 3 days';
INTERVAL '2 weeks ago';

ISO 8601 interval format

In addition to the verbose syntax above, PostgreSQL allows you to write the interval values using ISO 8601 time intervals in two ways: format with designators and alternative format.

The ISO 8601 format with designators is like this:

1
P quantity unit [ quantity unit ...] [ T [ quantity unit ...]]

In this format, the interval value must start with the letter P. The letter T is for determining time-of-day unit.

The following table illustrates the ISO 8601 interval unit abbreviations:

AbbreviationDescription
YYears
MMonths (in the date part)
WWeeks
DDays
HHours
MMinutes (in the time part)
SSeconds

Note that M can be months or minutes depending on whether it appears before or after the letter T.

For example, the interval of 6 years 5 months 4 days 3 hours 2 minutes 1 second can be written in the ISO 8601 designators format as follows:

1
P6Y5M4DT3H2M1S

The alternative form of ISO 8601 is:

1
P [ years-months-days ] [ T hours:minutes:seconds ]

It also must start with the letter P, and the letter T separates the date and time parts of the interval value. For example, the interval of 6 years 5 months 4 days 3 hours 2 minutes 1 second can be written in the ISO 8601 alternative form as:

1
P0006-05-04T03:02:01

PostgreSQL interval output format

The output style of interval values is set by using the SET intervalstyle command, for example:

1
SET intervalstyle = 'sql_standard';

PostgreSQL provides four output formats: sql standard, postgres, postgresverbose, and iso_8601. PostgresQL uses the postgres style by default for formatting the interval values.

The following represents the interval of 6 years 5 months 4 days 3 hours 2 minutes 1 second in the four styles:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
SET intervalstyle = 'sql_standard';
 
SELECT
INTERVAL '6 years 5 months 4 days 3 hours 2 minutes 1 second';
 
 
SET intervalstyle = 'postgres';
 
SELECT
INTERVAL '6 years 5 months 4 days 3 hours 2 minutes 1 second';
 
 
SET intervalstyle = 'postgres_verbose';
 
SELECT
INTERVAL '6 years 5 months 4 days 3 hours 2 minutes 1 second';
 
 
SET intervalstyle = 'iso_8601';
 
SELECT
INTERVAL '6 years 5 months 4 days 3 hours 2 minutes 1 second';

sql standardpostgrespostgres verboseiso_8601
 +6-5 +4 +3:02:01  6 years 5 mons 4 days 03:02:01  @ 6 years 5 mons 4 days 3 hours 2 mins 1 sec  P6Y5M4DT3H2M1S

PostgreSQL interval related operators and functions

Interval operators

You can apply the arithmetic operator ( +, -, *, etc.,) to the interval values, for examples:

1
2
3
4
5
6
7
8
SELECT
INTERVAL '2h 50m' + INTERVAL '10m'; -- 03:00:00
 
SELECT
INTERVAL '2h 50m' - INTERVAL '50m'; -- 02:00:00
 
SELECT
600 * INTERVAL '1 minute'; -- 10:00:00

Converting PostgreSQL interval to string

To convert an interval value to string, you use the to_char function.

1
to_char(interval,pattern)

The to_char function takes the first argument as an interval value, the second one as the pattern, and return a string that represents the interval in the specified pattern.

See the following example:

1
2
3
4
5
SELECT
    to_char(
        INTERVAL '17h 20m 05s',
        'HH24:MI:SS'
    );

It returned the following output:

1
2
3
4
to_char
----------
17:20:05
(1 row)

Extracting data from a PostgreSQL interval

To extract data such as year, month, date, etc., from an interval, you use the extract function.

1
EXTRACT(field FROM interval)

The field can be year, month, date, hour, minutes, etc., that you want to extract from the interval. The extract function returns a value of type double precision.

See the following example:

1
2
3
4
5
6
SELECT
    EXTRACT (
        MINUTE
        FROM
            INTERVAL '5 hours 21 minutes'
    );

In this example, we extracted the minute from the interval of 5 hours 21 minutes and it returned 21 as expected:

1
2
3
4
date_part
-----------
        21
(1 row)

Adjusting interval values

PostgreSQL provides two functions justifydays and  justifyhours that allow you to adjust the interval of 30-day as one month and the interval of 24-hour as one day:

1
2
3
SELECT
    justify_days(INTERVAL '30 days'),
    justify_hours(INTERVAL '24 hours');

1
2
3
4
justify_days | justify_hours
--------------+---------------
1 mon        | 1 day
(1 row)

In addition, the justify_interval function adjusts interval using justifydays and  justifyhours with additional sign adjustments:

1
2
SELECT
    justify_interval(interval '1 year -1 hour');

1
2
3
4
     justify_interval
--------------------------
11 mons 29 days 23:00:00
(1 row)

In this tutorial, you have learned about the PostgreSQL interval data type and how to manipulate interval values.

Previous Tutorial: Understanding PostgreSQL Timestamp Data Types
Next Tutorial: A Quick Guide To The PostgreSQL TIME Data Type

PostgreSQL Quick Start

  • What is PostgreSQL?
  • Install PostgreSQL
  • Connect to Database
  • Download PostgreSQL Sample Database
  • Load Sample Database
  • Explore Server and Database Objects

PostgreSQL Fundamentals

  • PostgreSQL Select
  • PostgreSQL Order By
  • PostgreSQL Select Distinct
  • PostgreSQL Where
  • PostgreSQL LIMIT
  • PostgreSQL IN
  • PostgreSQL Between
  • PostgreSQL Like
  • PostgreSQL Inner Join
  • PostgreSQL Left Join
  • PostgreSQL Full Outer Join
  • PostgreSQL Cross Join
  • PostgreSQL Natural Join
  • PostgreSQL Group By
  • PostgreSQL Having
  • PostgreSQL Union
  • PostgreSQL Intersect
  • PostgreSQL Except
  • PostgreSQL Subquery
  • PostgreSQL Insert
  • PostgreSQL Update
  • PostgreSQL Delete
  • PostgreSQL Data Types
  • PostgreSQL Create Table
  • PostgreSQL Alter Table
  • PostgreSQL Drop Table
  • PostgreSQL Truncate Table
  • PostgreSQL CHECK Constraint
  • PostgreSQL Not-Null Constraint
  • PostgreSQL Foreign Key
  • PostgreSQL Primary Key
  • PostgreSQL UNIQUE Constraint

About PostgreSQL Tutorial

PostgreSQLTutorial.com is a website dedicated to developers and database administrators who are working on PostgreSQL database management system.

We constantly publish useful PostgreSQL tutorials to keep you up-to-date with the latest PostgreSQL features and technologies. All PostgreSQL tutorials are simple, easy-to-follow and practical.

Recent PostgreSQL Tutorials

  • PostgreSQL UPDATE Join with A Practical Example
  • PostgreSQL Cheat Sheet
  • PostgreSQL vs. MySQL
  • A Step-by-Step Guide To PostgreSQL Temporary Table
  • PostgreSQL RENAME COLUMN: Renaming One or More Columns of a Table
  • PostgreSQL Rename Table: A Step-by-Step Guide
  • PostgreSQL Change Column Type: Step-by-Step Examples
  • PostgreSQL DROP COLUMN: Remove One or More Columns of a Table
  • A Quick Guide To The PostgreSQL TIME Data Type
  • A Comprehensive Look at PostgreSQL Interval Data Type

More Tutorials

  • PostgreSQL Cheat Sheet
  • PostgreSQL Administration
  • PostgreSQL PHP
  • PostgreSQL Python
  • PostgreSQL JDBC
  • PostgreSQL Resources

Site Info

  • Home
  • About Us
  • Contact Us
  • Privacy Policy

Copyright © 2017 by PostgreSQL Tutorial Website. All Rights Reserved.