16

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?

asked Dec 22, 2016 at 8:36

4 Answers 4

22

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:

answered Dec 22, 2016 at 18:12
2
  • I find something about the arbitrary date to be very ugly. But, I was thinking it would in fact be quicker and better too. Commented Dec 22, 2016 at 18:14
  • Since the date is irrelevant, it may as well be arbitrary. It's the fastest way. Commented Dec 22, 2016 at 18:16
8

Not sure if this is the best way, but we can use generate_series to generate the min-offset from 00:00:00 and then simply call make_interval(mins=>) to get the interval from it.

SELECT make_interval(mins=>x)::time
FROM generate_series(0, 60*24-5, 5) AS t(x);
answered Dec 22, 2016 at 8:36
4

I liked @EvanCarroll way, but yet another option -

select x::time
from generate_series 
 (current_date,current_date + '1 day - 1 second'::interval,'5 minute') as t(x);
answered Dec 22, 2016 at 8:53
1
  • 1
    This will only work sometimes in someplaces. It's subject to DST borking. See my answer here for more information. Commented Jun 12, 2017 at 18:19
3

Another way:

SELECT '00:00:00'::time + x * '1 minute'::interval
FROM generate_series(0, 60*24, 5) AS t(x);
answered Dec 22, 2016 at 8:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.