OVERLAPS Predicate Time Intervals
The SQL-standard OVERLAPS predicate compares two (start, end) interval pairs with half-open semantics, no range types required.
Code
SELECT (TIME '09:00', TIME '10:30') OVERLAPS (TIME '10:00', TIME '11:00') AS truly_overlaps,
(TIME '09:00', TIME '10:00') OVERLAPS (TIME '10:00', TIME '11:00') AS touching_is_false,
(TIME '09:00', TIME '10:30') OVERLAPS (TIME '09:00', TIME '10:30') AS identical_is_true;
-- 排班表:找出与目标班次重叠的轮班,谓词直接写进 WHERE
CREATE TABLE shifts (
shift_id int PRIMARY KEY,
worker text NOT NULL,
starts_at time NOT NULL,
ends_at time NOT NULL
);
INSERT INTO shifts VALUES
(1, 'ada', TIME '09:00', TIME '12:00'),
(2, 'lin', TIME '11:30', TIME '14:00'),
(3, 'kai', TIME '14:00', TIME '18:00');
SELECT shift_id, worker, starts_at, ends_at
FROM shifts
WHERE (starts_at, ends_at) OVERLAPS (TIME '10:00', TIME '13:00')
ORDER BY shift_id;
DROP TABLE shifts;Inside the snippet
Several statements share this file — SELECT / INSERT / CREATE, with shifts among the objects involved.
Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
The shifts table is the working surface here.
Core lines
SELECT shift_id, worker, starts_at, ends_at
FROM shifts
WHERE (starts_at, ends_at) OVERLAPS (TIME '10:00', TIME '13:00')
ORDER BY shift_id;
SELECT (TIME '09:00', TIME '10:30') OVERLAPS (TIME '10:00', TIME '11:00') AS truly_overlaps,
(TIME '09:00', TIME '10:00') OVERLAPS (TIME '10:00', TIME '11:00') AS touching_is_false,
(TIME '09:00', TIME '10:30') OVERLAPS (TIME '09:00', TIME '10:30') AS identical_is_true;
INSERT INTO shifts VALUES
(1, 'ada', TIME '09:00', TIME '12:00'),
(2, 'lin', TIME '11:30', TIME '14:00'),
(3, 'kai', TIME '14:00', TIME '18:00');
Interactive Tools for This Topic
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.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.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
FAQ
- Which relations are involved here?
- `shifts` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.