HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

How do I generate a time series in PostgreSQL?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqltimegeneratehowseries

Problem

If you're looking to generate a date series, see this question

Let's say I want to generate a series for every 5 minutes for 24 hours. How do I do that in PostgreSQL?

PostgreSQL can generate_series() from a timestamp, but not from time.

Is it better to pick an arbitrary timestamp, or is there another way to generate the series?

Solution

To optimize:

SELECT x::time
FROM   generate_series(timestamp '2000-01-01'
                     , timestamp '2000-01-02'
                     , interval  '5 min') t(x);


The date is irrelevant, so use arbitrary timestamp constants. The cast to time is very cheap.

This includes lower and upper bound, so we get '00:00' twice. Use '2000-01-01 23:59' as upper bound to get it once only.

Related:

  • Generating time series between two dates in PostgreSQL

Code Snippets

SELECT x::time
FROM   generate_series(timestamp '2000-01-01'
                     , timestamp '2000-01-02'
                     , interval  '5 min') t(x);

Context

StackExchange Database Administrators Q#158907, answer score: 22

Revisions (0)

No revisions yet.