On Tue, Mar 24, 2020 at 9:34 PM Tels <nospam-pg-ab...@bloodgate.com> wrote: > > Hello John, > > this looks like a nice feature. I'm wondering how it relates to the > following use-case: > > When drawing charts, the user can select pre-defined widths on times > (like "15 min", "1 hour"). > > The data for these slots is fitted always to intervalls that start in 0 > in the slot, e.g. if the user selects "15 min", the interval always > starts at xx:00, xx:15, xx:30 or xx:45. This is to aid caching of the > resulting data, and so that requesting the same chart at xx:00 and xx:01 > actually draws the same chart, and not some bar with only one minute > data at at the end.
Hi Tels, thanks for your interest! Sounds like the exact use case I had in mind. > It is of course easy for things like "1 hour", but for yearly I had to > come up with things like: > > EXTRAC(YEAR FROM thetime) * 12 + EXTRACT(MONTH FROM thetime) > > and its gets even more involved for weeks, weekdays or odd things like > fortnights. To be clear, this particular case was already handled by the existing date_trunc, but only single units and a few other special cases. I understand if you have to write code to handle 15 minutes, you need to use that structure for all cases. Fortnight would be trivial: date_trunc_interval('14 days'::interval, thetime [, optional start of the fortnight]) ...but weekdays would still need something extra. > So would that mean one could replace this by: > > date_trunc_interval('3600 seconds'::interval, thetime) > > and it would be easier, and (hopefully) faster? Certainly easier and more flexible. It's hard to make guesses about performance, but with your example above where you have two SQL function calls plus some expression evaluation, I think a single function would be faster in many cases. -- John Naylor https://www.2ndQuadrant.com/ PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services