daterange Canonicalizes Discrete Bounds
daterange folds inclusive upper bounds to next-day exclusive form, reports emptiness with isempty, and joins touching bookings with the -|- adjacency operator.
Code
-- 离散范围类型统一规范成 [) 形式:闭上界自动折成"次日开区间"
SELECT daterange('2026-11-20', '2026-11-25', '[]') AS closed_input,
daterange('2026-11-20', '2026-11-25') AS canonical;
-- 规范化后下界恒为闭:lower_inc 对任何 daterange 都返回 true
-- 闭区间 [11-20,11-26) 与次日区间 [11-25,11-28) 在 25 号重叠(&& 为 true),
-- 但邻接要求前段上界等于后段下界(11-26 ≠ 11-25),-|- 为 false
SELECT lower_inc(daterange('2026-11-20', '2026-11-25', '[]')) AS lower_inc_always_true,
daterange('2026-11-20', '2026-11-25', '[]') && daterange('2026-11-25', '2026-11-28') AS overlap_yes,
daterange('2026-11-20', '2026-11-25', '[]') -|- daterange('2026-11-25', '2026-11-28') AS adjacent_no;
-- 起点不小于终点时整体塌缩为空:isempty 判空
SELECT isempty(daterange('2026-11-25', '2026-11-20')) AS inverted_is_empty,
isempty(daterange('2026-11-25', '2026-11-25')) AS half_open_empty,
isempty(daterange('2026-11-25', '2026-11-26')) AS one_day_not_empty;
-- 相邻而非重叠:&& 是 false,-|- 是 true,两个订区间可以无缝衔接
SELECT daterange('2026-11-20', '2026-11-25') && daterange('2026-11-25', '2026-11-28') AS overlaps,
daterange('2026-11-20', '2026-11-25') -|- daterange('2026-11-25', '2026-11-28') AS touches;How it works
The file runs constructor and predicate calls over date literals; no table is involved, so any PostgreSQL session can run it as-is.
The first statement shows canonicalization: a daterange built with the closed flag ‘[]’ is stored in the standard [) form, its upper bound folded from the inclusive 11-25 to the exclusive 11-26.
Overlap versus adjacency
Because the closed booking spans the 25th after canonicalization, && against the next-day range is true while -|- is false — the two bookings collide rather than touch. The final statement repeats the comparison with already-canonical [) ranges, where the upper bound of the first equals the lower bound of the second: && is false and -|- is true.
Key statements
SELECT lower_inc(daterange('2026-11-20', '2026-11-25', '[]')) AS lower_inc_always_true;
SELECT isempty(daterange('2026-11-25', '2026-11-25')) AS half_open_empty;
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.