// dates & times reference

SQL OVERLAPS operator

Booking clashes, shift conflicts and validity windows all reduce to one question: do two time ranges overlap?

Категория
Dates & times
Returns
boolean
In this category
121 of 121

Синтаксис

(start1, end1) OVERLAPS (start2, end2)

Поддержка движка

ДвижокSupportЗаметки
SQL Server Not built in no; start1 < end2 AND start2 < end1
PostgreSQL Да Supported under this name.
MySQL Not built in no; start1 < end2 AND start2 < end1
SQLite Not built in no; start1 < end2 AND start2 < end1
Oracle Different name or syntax accepted by 23ai but not in the SQL Language Reference; use the comparison

Примеры

PostgreSQL

SELECT (DATE '2026-01-01', DATE '2026-01-10') OVERLAPS (DATE '2026-01-10', DATE '2026-01-20') AS touching,
       (DATE '2026-01-01', DATE '2026-01-10') OVERLAPS (DATE '2026-01-09', DATE '2026-01-20') AS overlapping;  -- f, t

SQL Server

DECLARE @s1 date = '2026-01-01', @e1 date = '2026-01-10', @s2 date = '2026-01-09', @e2 date = '2026-01-20';
SELECT CASE WHEN @s1 < @e2 AND @s2 < @e1 THEN 'overlap' ELSE 'none' END AS result;  -- overlap

PostgreSQL

SELECT daterange('2026-01-01', '2026-01-10') && daterange('2026-01-10', '2026-01-20') AS touching;  -- f

Полезно знать

  • Ranges are half-open: (Jan 1, Jan 10) and (Jan 10, Jan 20) share only an endpoint, and OVERLAPS returns false.
  • A zero-length range is the exception: (Jan 5, Jan 5) overlaps (Jan 5, Jan 6).
  • If a pair is written end first, OVERLAPS swaps it. The hand-written comparison does not, so validate start <= end on input.
  • In PostgreSQL, range types do the same job with index support: daterange(a, b) && daterange(c, d), backed by a GiST index.

Questions about OVERLAPS

How do I find overlapping bookings?

Self-join on the room: FROM bookings a JOIN bookings b ON a.room = b.room AND a.id < b.id AND a.start_at < b.end_at AND b.start_at < a.end_at.

Should the end of a range be inclusive?

Store half-open ranges (end excluded). Back-to-back bookings then do not clash, and the overlap test needs no +1 adjustments.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.