Skip to content
Advertisement

How to split time intervals by day in PostgreSQL

I have a query that returns some device state information with device id and timestamp. I am trying to do some daily reports and for that I need to know what state devices were in during the day. So, for example, my query might get me something like this

what I want to end up with is

What I tried, is something like this

Essentially, I right join a sequence of days using overlap function, so every interval that overlaps with that day generates a row and then I cut intervals at the day borders.

Then I use this as a nested select for my daily calculations.

The problem with this approach is that the right join generates a lot of records and the join filter then takes forever. Here is a piece of explain analyze output

As you can see, it generated about 5 million rows, filtered them down to 41K rows and the operation took some 32 seconds.

Is there a more efficient solution to this problem?

Advertisement

Answer

This should be faster than your current approach:

You can use a subquery to get the exact date/times that you want.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement