How justify_interval() Works in PostgreSQL

In PostgreSQL, the justify_interval() function adjusts an interval using justify_days and justify_hours. It allows you to use additional sign adjustments to adjust the interval.

Syntax

The function has the following syntax:

justify_interval(interval)

Where interval is the interval that you want adjusted.

Example

Here’s a basic example to demonstrate.

SELECT justify_interval(interval '1 mon -3 hours');

Result:

29 days 21:00:00

Comparison with justify_hours() and justify_days()

Here’s how it compares to justify_hours() and justify_days() when using the same argument.

\x
SELECT 
  justify_interval(interval '1 mon -3 hours'),
  justify_hours(interval '1 mon -3 hours'),
  justify_days(interval '1 mon -3 hours');

Result (using vertical output):

justify_interval | 29 days 21:00:00
justify_hours    | 1 mon -03:00:00
justify_days     | 1 mon -03:00:00

In this example I used \x to switch over to expanded display, which displays the results using vertical output.

Below are some more comparisons using various arguments.

justify_interval()

SELECT 
  justify_interval(interval '30 hours'),
  justify_interval(interval '300 hours'),
  justify_interval(interval '3000 hours'),
  justify_interval(interval '3.53 months'),
  justify_interval(interval '18 days'),
  justify_interval(interval '31 days'),
  justify_interval(interval '45 days'),
  justify_interval(interval '290 days');

Result (using vertical output):

justify_interval | 1 day 06:00:00
justify_interval | 12 days 12:00:00
justify_interval | 4 mons 5 days
justify_interval | 3 mons 15 days 21:36:00
justify_interval | 18 days
justify_interval | 1 mon 1 day
justify_interval | 1 mon 15 days
justify_interval | 9 mons 20 days

justify_hours()

SELECT 
  justify_hours(interval '30 hours'),
  justify_hours(interval '300 hours'),
  justify_hours(interval '3000 hours'),
  justify_hours(interval '3.53 months'),
  justify_hours(interval '18 days'),
  justify_hours(interval '31 days'),
  justify_hours(interval '45 days'),
  justify_hours(interval '290 days');

Result (using vertical output):

justify_hours | 1 day 06:00:00
justify_hours | 12 days 12:00:00
justify_hours | 125 days
justify_hours | 3 mons 15 days 21:36:00
justify_hours | 18 days
justify_hours | 31 days
justify_hours | 45 days
justify_hours | 290 days

justify_days()

SELECT 
  justify_days(interval '30 hours'),
  justify_days(interval '300 hours'),
  justify_days(interval '3000 hours'),
  justify_days(interval '3.53 months'),
  justify_days(interval '18 days'),
  justify_days(interval '31 days'),
  justify_days(interval '45 days'),
  justify_days(interval '290 days');

Result (using vertical output):

justify_days | 30:00:00
justify_days | 300:00:00
justify_days | 3000:00:00
justify_days | 3 mons 15 days 21:36:00
justify_days | 18 days
justify_days | 1 mon 1 day
justify_days | 1 mon 15 days
justify_days | 9 mons 20 days