// SQL snippet

Detect overlapping date ranges

Two half-open ranges overlap when each starts before the other ends; a self-join with that condition pairs every colliding row.

Main statement
All engines

The task

subscriptions stores start_date and end_date per customer, and business rules say a customer holds at most one active subscription. Imports may have created colliding periods.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT a.id AS first_id, a.customer_id,
       a.start_date AS first_start, a.end_date AS first_end,
       b.id AS colliding_id,
       b.start_date AS second_start, b.end_date AS second_end
FROM subscriptions a
JOIN subscriptions b
  ON a.id < b.id
 AND a.customer_id = b.customer_id
 AND a.start_date < b.end_date
 AND b.start_date < a.end_date
ORDER BY a.customer_id, a.start_date;

Cómo funciona

The a.id < b.id condition pairs each row once (A with B, never B with A) and skips self-pairs. The two range tests are the standard half-open overlap predicate: A starts before B ends AND B starts before A ends. Restricting to equal customer_id scopes the check per customer. An open-ended subscription stored with a NULL end_date never matches; wrap it as COALESCE(end_date, DATE '9999-12-31') (a plain '9999-12-31' string on SQL Server and SQLite) to treat it as running forever.

Variations

Closed ranges (end dates inclusive)

SELECT a.id, b.id AS colliding_id, a.customer_id
FROM subscriptions a
JOIN subscriptions b
  ON a.id < b.id
 AND a.customer_id = b.customer_id
 AND a.start_date <= b.end_date
 AND b.start_date <= a.end_date;

Overlap size in days (PostgreSQL, Oracle: date minus date is a day count)

PostgreSQL Oracle
SELECT a.id, b.id AS colliding_id,
       LEAST(a.end_date, b.end_date) - GREATEST(a.start_date, b.start_date) AS overlap_days
FROM subscriptions a
JOIN subscriptions b
  ON a.id < b.id
 AND a.customer_id = b.customer_id
 AND a.start_date < b.end_date
 AND b.start_date < a.end_date;

Questions that come up

Why the strict inequality a.start_date < b.end_date?

Because the ranges are half-open: a subscription ending 2026-03-01 and one starting 2026-03-01 do not truly collide; the second begins the instant the first ends. Strict comparisons treat that handoff as legal. If your end dates are inclusive, switch both comparisons to <= with the first variant.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.