Multirange Type Merged Segments

Store non-contiguous slots in one multirange value: overlaps merge on construction, containment and intersection work across all segments.

SqlData Integrity

Code

snippet
-- PG14+ 的 multirange:一段变量里存多个不连续区间
SELECT '{[8,10),[12,14)}'::int4multirange AS schedule,
       '{[8,10),[9,11)}'::int4multirange AS auto_merged;

-- 交集/包含跨所有成员段一次判断
SELECT '{[8,10),[12,14)}'::int4multirange * '{[9,13)}'::int4multirange AS intersection,
       '{[8,10),[12,14)}'::int4multirange @> 13 AS contains_13,
       '{[8,10),[12,14)}'::int4multirange @> 11 AS contains_11;

-- 排期表:一条请假记录可以含多个时间段,重叠自动合并
CREATE TABLE time_off (
    person  text PRIMARY KEY,
    windows datemultirange NOT NULL
);

INSERT INTO time_off VALUES
    ('ada', datemultirange(daterange('2026-11-16', '2026-11-18'),
                           daterange('2026-11-17', '2026-11-20')));

SELECT person, windows::text FROM time_off;

-- 谁在 11-19 休假:multirange 对标量直接做包含判断,跨所有成员段
SELECT person
FROM time_off
WHERE windows @> '2026-11-19'::date;

DROP TABLE time_off;

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with time_off among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the time_off table.

Statements that matter

SELECT person
FROM time_off
WHERE windows @> '2026-11-19'::date;
SELECT '{[8,10),[12,14)}'::int4multirange * '{[9,13)}'::int4multirange AS intersection,
'{[8,10),[12,14)}'::int4multirange @> 13 AS contains_13,
'{[8,10),[12,14)}'::int4multirange @> 11 AS contains_11;
INSERT INTO time_off VALUES
('ada', datemultirange(daterange('2026-11-16', '2026-11-18'),
daterange('2026-11-17', '2026-11-20')));

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`time_off` — referenced directly, no join needed.