Home > Database > Mysql Tutorial > How to Efficiently Generate Time Series Between Dates in PostgreSQL?

How to Efficiently Generate Time Series Between Dates in PostgreSQL?

Susan Sarandon
Release: 2025-01-21 16:51:08
Original
260 people have browsed it

How to Efficiently Generate Time Series Between Dates in PostgreSQL?

PostgreSQL date interval time series generation method

When PostgreSQL processes time series data, it is often necessary to generate a series of dates between two given dates. A common method is to use the generate_series() function.

<code class="language-sql">select date '2004-03-07' + j - i as AllDate 
from generate_series(0, extract(doy from date '2004-03-07')::int - 1) as i,
     generate_series(0, extract(doy from date '2004-08-16')::int - 1) as j</code>
Copy after login

However, this approach sometimes encounters limitations when dealing with dates that span different years. To effectively resolve this situation, consider the following:

<code class="language-sql">SELECT date_trunc('day', dd):: date
FROM generate_series
        ( '2007-02-01'::timestamp 
        , '2008-04-01'::timestamp
        , '1 day'::interval) dd
        ;</code>
Copy after login

This query generates a range of dates between the given timestamps, converting them into a recognized date format before returning them. It maintains accuracy even when two dates span multiple years.

The above is the detailed content of How to Efficiently Generate Time Series Between Dates in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template