CTE Self Join Detects Overlapping Shifts

Prepare the candidate set once in a CTE, then reference it twice in a self-join with a shift_id guard so each overlapping pair is reported exactly once.

SqlData Integrity

Code

snippet
CREATE TEMP TABLE shifts (
    shift_id  int PRIMARY KEY,
    worker    text NOT NULL,
    starts_at timestamptz NOT NULL,
    ends_at   timestamptz NOT NULL
);
INSERT INTO shifts VALUES
    (1, 'ada', '2026-11-19 09:00+00', '2026-11-19 12:00+00'),
    (2, 'lin', '2026-11-19 11:30+00', '2026-11-19 14:00+00'),
    (3, 'kai', '2026-11-19 14:00+00', '2026-11-19 18:00+00'),
    (4, 'noa', '2026-11-19 15:00+00', '2026-11-19 17:00+00');

-- 同一个 CTE 引用两次做 self join:先把候选集规整好,
-- 再对同一份结果两两比较,detect 互相 overlapping 的 shift 对
WITH todays_shifts AS (
    SELECT shift_id, worker, starts_at, ends_at
    FROM shifts
    WHERE starts_at >= '2026-11-19' AND starts_at < '2026-11-20'
)
SELECT a.shift_id AS shift_a, a.worker AS worker_a,
       b.shift_id AS shift_b, b.worker AS worker_b
FROM todays_shifts a
JOIN todays_shifts b
  ON a.shift_id < b.shift_id        -- 只比一次,(1,2) 与 (2,1) 不重复
 AND a.starts_at < b.ends_at        -- 半开区间:端点相接不算冲突
 AND b.starts_at < a.ends_at
ORDER BY a.shift_id, b.shift_id;
-- 命中 (1,2) 与 (3,4);2↔3 在 14:00 端点相接,不进结果
DROP TABLE shifts;

How it works

What runs here is SELECT / INSERT / CREATE — shifts and todays_shifts are the objects involved.

shifts exists only because this script declares it as a session-local temp table — nothing precedes it, and the session closing clears it away.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The file sets up its own scratch surface: it builds the session-local tables it works with (shifts), so one full run against a throwaway database is enough.

Statements that matter

INSERT INTO shifts VALUES
    (1, 'ada', '2026-11-19 09:00+00', '2026-11-19 12:00+00'),
    (2, 'lin', '2026-11-19 11:30+00', '2026-11-19 14:00+00'),
    (3, 'kai', '2026-11-19 14:00+00', '2026-11-19 18:00+00'),
    (4, 'noa', '2026-11-19 15:00+00', '2026-11-19 17:00+00');
CREATE TEMP TABLE shifts (
    shift_id  int PRIMARY KEY,
    worker    text NOT NULL,
    starts_at timestamptz NOT NULL,
    ends_at   timestamptz NOT NULL
);
DROP TABLE shifts;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `shifts`, `todays_shifts`, with one join tying the pair together.