A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-date-difference.php below:

Website Navigation


Understanding Date Differences in PostgreSQL with Examples

Understanding Date Differences in PostgreSQL with ExamplesLast update on December 31 2024 05:34:49 (UTC/GMT +8 hours)

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:

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

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