postgresqlHow do I use PostgreSQL's interval data type?
PostgreSQL's interval data type is used to store and manipulate time intervals. It is useful when you need to store a length of time as a single value, such as the duration of a movie.
An interval value is specified using the syntax INTERVAL 'value' unit, where value is the length of the interval and unit is the unit of time such as DAY, MONTH, YEAR etc. For example, INTERVAL '3 DAYS' represents a length of time of 3 days.
Let's look at an example of how to use the interval data type. We will create a table called movies with a column called duration that stores the duration of the movie in days as an interval.
CREATE TABLE movies (
title VARCHAR(50),
duration INTERVAL
);
We can then insert a movie into the table with a duration of 3 days:
INSERT INTO movies (title, duration)
VALUES ('The Godfather', INTERVAL '3 DAYS');
We can also retrieve the duration of the movie by using a SELECT statement:
SELECT title, duration
FROM movies;
Output example
title | duration
--------------+------------
The Godfather | 3 days
Code explanation
CREATE TABLE- used to create a table with a column of typeINTERVALINSERT INTO- used to insert a movie with a duration as an intervalSELECT- used to retrieve the duration of a movie
Helpful links
More of Postgresql
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How can I set a PostgreSQL interval to zero?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I retrieve data from PostgreSQL for yesterday's date?
- How do I use PostgreSQL's XMIN and XMAX features?
- How do I use PostgreSQL's XMLTABLE to parse XML data?
- How can I use PostgreSQL XOR to compare two values?
- How can I monitor PostgreSQL performance using Zabbix?
- How can I integrate PostgreSQL with Yii2?
- How can I use PostgreSQL with YAML?
See more codes...