w3resource

Understanding Date Differences in PostgreSQL with Examples


PostgreSQL Date Difference: Calculating Time Intervals

In PostgreSQL, you can calculate the difference between two dates or timestamps using built-in functions and operations. The result is typically expressed in terms of days, hours, or a full interval, depending on the specific requirement. This guide will cover the syntax, examples, and use cases for calculating date differences in PostgreSQL.


Syntax:

    1. Basic Date Difference Using Subtraction

    SELECT date1 - date2 AS difference;
    

    2. Using the AGE Function for Full Interval

    SELECT AGE(date1, date2) AS interval_difference;
    

    3. Extracting Specific Units (e.g., days, months, etc.)

    SELECT EXTRACT(EPOCH FROM (date1 - date2)) / (60 * 60 * 24) AS days_difference;
    

Examples and Code:

1. Difference Between Two Dates

Code:

-- Create a table to store sample data
CREATE TEMP TABLE sample_dates (
    id SERIAL PRIMARY KEY, -- Primary key for the table
    start_date DATE,       -- Column for the starting date
    end_date DATE          -- Column for the ending date
);

-- Insert sample data
INSERT INTO sample_dates (start_date, end_date)
VALUES 
('2023-11-01', '2023-11-15'),
('2023-10-01', '2023-12-01');

-- Calculate the date difference in days
SELECT 
    id, 
    end_date - start_date AS difference_in_days 
FROM sample_dates;

Output:

id	difference_in_days
1	14
2	61

2. Using the AGE Function for Interval Differences

Code:

-- Calculate the interval difference between two dates
SELECT 
    id, 
    AGE(end_date, start_date) AS interval_difference 
FROM sample_dates;

Output:

id	interval_difference
1	14 days
2	2 mons

3. Extracting Specific Units (e.g., Days)

Code:

-- Extract the difference in days explicitly
SELECT 
    id, 
    EXTRACT(DAY FROM (end_date - start_date)) AS days_only 
FROM sample_dates;

Output:

id	days_only
1	14
2	1

Explanation

    1. Subtraction Operator (-):
    This operator calculates the direct difference between two DATE types, providing results in days.

    2. AGE Function:

    • Returns the difference in an INTERVAL format, showing months, days, and even seconds if needed.
    • It is helpful for capturing differences with precision in complex scenarios.

    3. EXTRACT Function:

    • Useful when you need specific time units like days, months, or years.
    • For example, extracting days from a calculated interval.

    4. Epoch Conversion:

    • If you need granular control, converting intervals to seconds using the EXTRACT(EPOCH FROM ...) function can help calculate differences in various units.

Use Cases

  • Task Duration Calculation: Determining the number of days required to complete a task.
  • Age Calculation: Using the AGE function for user or entity age determination.
  • Event Scheduling: Finding gaps between two events to plan the next activity.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Follow us on Facebook and Twitter for latest update.