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:
3. EXTRACT Function:
4. Epoch Conversion:
Use Cases
All PostgreSQL Questions, Answers, and Code Snippets Collection.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4