snippetsqlMajor
How do I generate a time series in PostgreSQL?
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
Is it better to pick an arbitrary timestamp, or is there another way to generate the series?
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:
The date is irrelevant, so use arbitrary timestamp constants. The cast to
This includes lower and upper bound, so we get
Related:
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.