I’m using Postgres and I would like to find missing range of dates. I’ve got this table with these data :
create table event_dates
(
date date
);
INSERT INTO event_dates (date) VALUES ('2024-12-09');
INSERT INTO event_dates (date) VALUES ('2024-12-13');
INSERT INTO event_dates (date) VALUES ('2024-12-20');
I would like to find the number of missing periods between an arbitrary range. For example,
between 2024-12-05 and 2024-12-25 I would like the result to be 4
, because :
- no dates between 2024-12-05 and 2024-12-09 (first gap)
- no dates between 2024-12-09 and 2024-12-13 (second gap)
- no dates between 2024-12-13 and 2024-12-20 (third gap)
- no dates between 2024-12-20 and 2024-12-25 (fourth gap)
I can’t get it work with ant window function.
Any clues ?
Thanks,
2
Answers
See example
fiddle
You may first create a list of all dates within the target range (use
generate_series
), then left joinevent_dates
to it and then discover which dates are start of a missing period using window functionlag
.DBV-Fiddle demo