EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL Interval
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL Interval

By Sohel SayyadSohel Sayyad

PostgreSQL Interval

Introduction to PostgreSQL Interval

We can store and manage the time period in seconds, minutes, hours, days, months, years, etc., by using the interval data type provided by PostgreSQL. The interval value is quite easy to understand, and it is human-readable. The interval value needs 16 bytes storage size, which stores a period with a low value of -178000000 years and a high value of 178000000 years. They provide us with different interval styles like Postgres, sql_standard, ISO-8601 postgres_verbose to format the interval value; by default, PostgreSQL uses Postgres style to format the interval values. PostgreSQL contains various functions to manipulate the interval value data; also, we can perform different arithmetic operations on an interval value.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

1. Interval Syntax

interval [ fields ] [ (p) ]

Explanation:

p: defines the number of fraction digits that should remain in the seconds. In the case of the interval types, the valid range for p is 0 to 6.

2. Interval value 

We can write the interval values with the help of the following syntax:

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

Explanation:

  • Quantity: Quantity defines a number that can be either positive or negative so that we can add + or – sign as well.
  • Unit: It can be any of the following:(decade, century, millennium), (week, month, year), (minute, hour, day), (microsecond, millisecond, second,) abbreviations like d, m, y, etc., plural forms like days, months, years etc.
  • Direction: The direction can be an empty string or ago.

How Does Interval Function Work in PostgreSQL?

1. PostgreSQL internally stores the interval values as seconds, days and months. The value of days and months is stored as integers, and the value of the second’s field might contain some fractions.

2. We can restrict the set of stored fields by using any of the following words in case of the interval type:

YEAR, MONTH, DAY, HOUR. MINUTE. SECOND. YEAR TO MONTH. DAY TO HOUR, DAY TO MINUTE, DAY TO SECOND, HOUR TO MINUTE, HOUR TO SECOND, MINUTE TO SECOND, etc.

3. The PostgreSQL provides various functions like TO_CHAR(), justify_days(), justify_hours(), justify_interval() and EXTRACT() etc. to manipulate the PostgreSQL interval value.

4. The value returned by the extract function retains double precision.

Examples to Implement Interval in PostgreSQL

1. Consider the following statements and snapshots, to begin with, examples of interval values:

Query:

select interval '6 months ago';

Output:

PostgreSQL Interval Example 1

Query:

select interval '2 hours 10 minutes';

Output:

PostgreSQL Interval Example 2

2. Consider the following statements and snapshots to know the time of 1 hour 10 minutes ago of the last two year at the current time.

Query:

SELECT
now(),  now() - INTERVAL '2 year 1 hours 10 minutes'  AS "Last year at current time 1 hours 10 minutes";

Output:

Current Time Example 2

3. PostgreSQL Interval operators

We can manipulate the interval values by using various arithmetic operators like +, -, *, etc.

Query:

SELECT
INTERVAL '3h 30m' + INTERVAL '20m';

Illustrate the result of the above statement with the help of the following snapshot:

Output:

Operators Example 3

Query:

SELECT
INTERVAL '4h 20m' - INTERVAL '30m';

Illustrate the result of the above statement with the help of the following snapshot:

Output:

Operators Example 3

Query:

SELECT
180 * INTERVAL '2 minute';

Illustrate the result of the above statement with the help of the following snapshot:

Output:

Operators Example 6

4. PostgreSQL interval value to string conversion

We can convert an interval value to the string by using a TO_CHAR() function provided by PostgreSQL as follows:

Syntax:

TO_CHAR(interval, format)

Explanation:

  • Interval: The interval value.
  • Format: the format to which we want to convert the interval value.

The TO_CHAR() function returns us the string of interval value converted in the specified format.

Consider the following statement to understand the TO_CHAR() function:

Query:

SELECT
TO_CHAR(
INTERVAL '10h 10m 10s',
'HH24:MI:SS'
);

Illustrate the result of the above statement with the help of the following snapshot:

Output:

String Conversion Example 4

5. Extract fields from a PostgreSQL interval value.

We can extract data like date, month, year, etc., from an interval value by using the EXTRACT() function provided by PostgreSQL.

Syntax:

EXTRACT(field FROM interval)

Explanation:

  • Field: This can be the minutes, hour, date, month, year, etc., which we want to extract.
  • Interval: The interval value.

Consider the following statement to understand the EXTRACT() function:

Query:

SELECT
EXTRACT (
MINUTE
FROM
INTERVAL '4 hours 11 minutes'
);

Here we have extracted the minute field as 4 hours 11 minutes, and as a result, we have got the expected minute value of 11.

Illustrate the result of the above statement with the help of the following snapshot:

Output:

PostgreSQL Interval Example 5

6. Adjust the PostgreSQL interval value.

We can use justify_days and justify_hours functions provided by PostgreSQL for adjusting the interval values.

Consider the the following statement to understand the justify_days() and justify_hours() functions:

Here we will adjust an interval value of 60 days and an interval value of 48 hours by using the justify_days() and justify_hours() functions.

Query:

SELECT
justify_days(INTERVAL '60 days'),
justify_hours(INTERVAL '48 hours');

Illustrate the result of the above statement with the help of the following snapshot:

Output:

PostgreSQL Interval Example 6

Also, PostgreSQL provides the justify_interval function, which will adjust interval value by using justify_days and justify_hours functions, having a sign adjustment as follows.

Query:

SELECT
justify_interval(interval '60 days -12 hour');

Illustrate the result of the above statement with the help of the following snapshot:

Output:

PostgreSQL Interval Example 6

Advantages

  1. The PostgreSQL interval values are helpful when we have to deal with date and time manipulation.
  2. We can use various functions provided by PostgreSQL like O_CHAR(), justify_days(), justify_hours(), justify_interval() and EXTRACT() etc. to manipulate the PostgreSQL interval value.
  3. As having the various function to deal with an interval in PostgreSQL, we can use it in scheduling mechanism.
  4. The interval data type is very easy and human-readable.
  5. We do not need to worry about managing the quantity – unit order, as explained in syntax in the interval; because of this, the handling of the interval is very easy.

Conclusion

We hope from the above article, you have understood how to use the PostgreSQL interval data type and how the PostgreSQL interval data type works to store the data. Also, we have added some examples of PostgreSQL intervals to understand them in detail.

Recommended Articles

This is a guide to PostgreSQL Interval. Here we discuss the Introduction to PostgreSQL Interval and the practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. How RANK() Function Works in PostgreSQL?
  2. How to Notify Works in PostgreSQL?
  3. PostgreSQL JSON (Examples)
  4. Introduction to PostgreSQL Timestamp
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more