Следующий запрос вернет все свободные интервалы для всех дней, для которых есть записи в reservation
:
WITH mins(lt) AS (
/* get all lower bounds of intervals */
SELECT lower(during)
FROM reservation
UNION
/* get 18:00 for each day */
SELECT date_trunc('day', lower(during)) + INTERVAL '18 hours'
FROM reservation
), maxs(ut) AS (
/* get all upper bounds of intervals */
SELECT upper(during)
FROM reservation
UNION
/* get 09:00 for each day */
SELECT date_trunc('day', lower(during)) + INTERVAL '9 hours'
FROM reservation
)
SELECT tsrange(ut, lt) /* candidate for a free interval */
FROM mins
JOIN maxs
ON date_trunc('day', lt) = date_trunc('day', ut)
AND ut < lt
/* exclude all such intervals that overlap an entry */
WHERE NOT EXISTS (SELECT 1 FROM reservation
WHERE during && tsrange(ut, lt, '()'))
ORDER BY ut;
Фильтрация их по длине оставлена читателю в качестве упражнения.