Multirange Type Merged Segments
Store non-contiguous slots in one multirange value: overlaps merge on construction, containment and intersection work across all segments.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- `time_off` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.