# Prevent Overlapping Date Ranges in PostgreSQL: EXCLUDE Constraint or WITHOUT OVERLAPS?

> On PostgreSQL 18 or later, declare the rule as a key, `PRIMARY KEY (room_id, during WITHOUT OVERLAPS)`, when other tables need to point at the history with a temporal foreign key. Keep an `EXCLUDE USING gist` constraint when the rule covers only some rows, has no key column, uses an operator other than overlap, or has to run on PostgreSQL 17.

Source: https://schemity.com/blog/postgres-prevent-overlapping-date-ranges-exclude-vs-without-overlaps/

To stop overlapping date ranges in PostgreSQL, put the period in a range column and let a GiST-backed constraint refuse the clash: `EXCLUDE USING gist (room_id WITH =, during WITH &&)` on any supported version, or `UNIQUE (room_id, during WITHOUT OVERLAPS)` on PostgreSQL 18 and later. The two refuse the same rows with the same error. The choice turns on what else the rule has to do: point a foreign key at it, skip cancelled rows, or run on PostgreSQL 17.

Everything below ran on PostgreSQL 18.3 and 19.0 in throwaway Docker containers, with identical results on both. The example is a hotel: rooms, bookings, and nightly rates that change over time.

## Why can't a unique constraint prevent overlapping bookings?

Because a unique constraint compares values for equality, and two bookings that overlap almost never have equal start or end times.

A booking from 10:00 to 12:00 and one from 11:00 to 13:00 clash, but `UNIQUE (room_id, starts_at)` sees two different start times and accepts both. The usual fallback is an application check, a `SELECT` for clashing bookings followed by the `INSERT`, which two concurrent requests both pass before either commits. A trigger has the same race unless it locks the room row first or runs at `SERIALIZABLE`. The database needs a rule that compares ranges with the overlap operator `&&`, which only an index-backed exclusion rule can enforce, and with an equality column beside the range that means a GiST index. The [CREATE TABLE manual](https://www.postgresql.org/docs/18/sql-createtable.html) documents both forms below.

Both constraints below need the [btree_gist](https://www.postgresql.org/docs/18/btree-gist.html) extension for the `bigint` column. Without it, PostgreSQL refuses either one with `data type bigint has no default operator class for access method "gist"`.

```sql
CREATE EXTENSION btree_gist;

CREATE TABLE room (
    id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);
INSERT INTO room (name) VALUES ('101');
```

## Prevent overlapping date ranges in PostgreSQL: the two declarations

An exclusion constraint says which operator must not be true between any two rows, and `WITHOUT OVERLAPS` says the same thing as part of a key.

The two tables below are alternatives: create one of them.

```sql
-- Any supported version
CREATE TABLE booking (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    room_id bigint NOT NULL REFERENCES room,
    during  tstzrange NOT NULL,
    CONSTRAINT booking_no_overlap EXCLUDE USING gist (room_id WITH =, during WITH &&)
);

-- PostgreSQL 18 and later, instead of the table above
CREATE TABLE booking (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    room_id bigint NOT NULL REFERENCES room,
    during  tstzrange NOT NULL,
    CONSTRAINT booking_no_overlap UNIQUE (room_id, during WITHOUT OVERLAPS)
);
```

With room 1 booked for `[2026-12-01 10:00+00, 2026-12-01 12:00+00)`, a second booking from 11:00 to 13:00 fails on both tables with the same message:

```
ERROR:  conflicting key value violates exclusion constraint "booking_no_overlap"
DETAIL:  Key (room_id, during)=(1, ["2026-12-01 11:00:00+00","2026-12-01 13:00:00+00")) conflicts with existing key (room_id, during)=(1, ["2026-12-01 10:00:00+00","2026-12-01 12:00:00+00")).
```

A booking from 12:00 to 13:00 is accepted by both, because the default `[)` bounds include the start and exclude the end, so back-to-back bookings touch without overlapping. The manual states the equivalence outright: `UNIQUE (id, valid_at WITHOUT OVERLAPS)` "behaves like `EXCLUDE USING GIST (id WITH =, valid_at WITH &&)`". The catalog agrees: the `EXCLUDE` version is stored as an exclusion constraint (`contype = 'x'`) backed by a GiST index, and the `WITHOUT OVERLAPS` version as a unique constraint (`contype = 'u'`, `conperiod = true`) backed by a unique GiST index.

## EXCLUDE vs WITHOUT OVERLAPS: which should you use?

Use `WITHOUT OVERLAPS` when the period is part of a row's identity and other tables will reference it; use `EXCLUDE` for every rule a key cannot express.

| | `EXCLUDE USING gist` | `WITHOUT OVERLAPS` key |
| --- | --- | --- |
| PostgreSQL version | Every supported version | 18 and later |
| Refuses an overlapping row | Yes | Yes |
| Back-to-back `[)` ranges | Allowed | Allowed |
| Range or multirange column | Any type the operator takes | Range or multirange only |
| Empty range (`'empty'`) | Allowed, overlaps nothing | **Refused**: `empty WITHOUT OVERLAPS value found` |
| `NULL` range | Passes the rule | Passes on `UNIQUE`; the `PRIMARY KEY` form makes the column `NOT NULL` |
| Only some rows (`WHERE status <> 'cancelled'`) | Yes, a partial constraint | **No**: syntax error at `WHERE` |
| Range column alone, no key column | Yes | **No**: `needs at least two columns` |
| Operators other than `=` and `&&` | Any the index supports, such as `-\|-` or geometric `&&` | No |
| Documented target of a `PERIOD` foreign key | No (18.3 and 19.0 accept it anyway) | Yes |
| Can be added `NOT VALID` | No | No |

So `EXCLUDE` keeps four jobs on PostgreSQL 18 and 19. A booking system that keeps cancelled rows needs the partial form, `EXCLUDE USING gist (room_id WITH =, during WITH &&) WHERE (status <> 'cancelled')`, and a cancelled and a confirmed booking for the same slot then coexist. A table of building-wide maintenance windows that must never overlap at all has no key column, `EXCLUDE USING gist (during WITH &&)`, which `WITHOUT OVERLAPS` refuses. A rule built on another operator, and anything on PostgreSQL 17, has only `EXCLUDE`.

Neither form stops a row whose range is `NULL`. On a nullable column, two rows for room 1 with a `NULL` period were both accepted by `EXCLUDE` and by `UNIQUE ... WITHOUT OVERLAPS`, the same rule that lets a unique constraint on a nullable column hold several `NULL`s. Declare the range `NOT NULL`, or use the `PRIMARY KEY` form, which does it for you.

## What does a temporal foreign key add?

A temporal foreign key makes a child row's period fall inside the parent's periods, and the manual documents a `WITHOUT OVERLAPS` key as the only thing it can reference.

Nightly rates change over time, and a stay must fall inside rates that exist:

```sql
CREATE TABLE room_rate (
    room_id bigint NOT NULL REFERENCES room,
    valid   daterange NOT NULL,
    nightly numeric(10,2) NOT NULL,
    PRIMARY KEY (room_id, valid WITHOUT OVERLAPS)
);

CREATE TABLE stay (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    room_id bigint NOT NULL,
    nights  daterange NOT NULL,
    FOREIGN KEY (room_id, PERIOD nights) REFERENCES room_rate (room_id, PERIOD valid)
);

INSERT INTO room_rate VALUES (1, '[2026-12-01,2026-12-15)', 120),
                             (1, '[2026-12-15,2027-01-01)', 180);
```

A stay for `[2026-12-10,2026-12-20)` is accepted, because the two rate rows together cover it: the key checks the combined periods, not a single row. A stay for `[2026-12-28,2027-01-03)` is refused with `violates foreign key constraint "stay_room_id_nights_fkey"`, because no rate covers January. Shrinking the second rate to `[2026-12-15,2026-12-18)` is refused too, with `is still referenced from table "stay"`, since the stay would lose two nights of cover.

Two limits come with it. A `PERIOD` foreign key accepts only `NO ACTION`, on delete and on update: `ON DELETE CASCADE` and even `ON DELETE RESTRICT` fail with `unsupported ON DELETE action for foreign key constraint using PERIOD`, and `ON UPDATE CASCADE` with the matching `ON UPDATE` error, so deleting or rewriting history is always the application's job. And while 18.3 and 19.0 both accepted a `PERIOD` key pointing at a plain `EXCLUDE` constraint, even one built on `-|-`, which guarantees no uniqueness at all, the manual says "the referenced table must have a primary key or unique constraint declared with `WITHOUT OVERLAPS`". Build on the documented target.

## How do you add the constraint to a table that already has overlaps?

Find and resolve the overlapping rows first, because neither constraint can be added while they exist and neither can be added `NOT VALID`.

Adding either form to a `booking` table that already holds two clashing rows fails with `could not create exclusion constraint "booking_no_overlap"` and names the two keys. Unlike a foreign key or a `CHECK`, an exclusion constraint has no `NOT VALID` escape: PostgreSQL answers `EXCLUDE constraints cannot be marked NOT VALID`. This query lists the pairs to fix:

```sql
SELECT a.id, b.id, a.room_id, a.during, b.during
FROM booking a
JOIN booking b ON a.room_id = b.room_id
              AND a.during && b.during
              AND a.id < b.id;
```

Which booking survives is a business decision, not a migration step. The `ALTER TABLE ... ADD CONSTRAINT` itself then builds the GiST index while holding an `ACCESS EXCLUSIVE` lock on the table, so reads and writes wait for the whole build. On a large table, schedule it like any other blocking schema migration.

## How does the overlap rule show up in a schema diagram?

Schemity reads both forms from a live PostgreSQL database and shows them on the table: a `WITHOUT OVERLAPS` key as a tag on the key, and an exclusion constraint as a read-only Exclusion row with its full definition.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. Connected to PostgreSQL 18 or 19, it keeps a `WITHOUT OVERLAPS` key and a `PERIOD` foreign key as declared, where they had been read as plain keys before. An exclusion constraint appears in the table's Unique constraints tab as its own row, tagged Exclusion, with the definition exactly as PostgreSQL prints it, operators and `WHERE` clause included. All of them are written back verbatim in `CREATE TABLE` and in migrations, and Import SQL reads the same forms from a `pg_dump`, inline or as `ALTER TABLE ... ADD CONSTRAINT`.

![Schemity's Update entity dialog for booking on a PostgreSQL diagram, Unique constraints tab: the row booking_no_overlap tagged Exclusion with the definition EXCLUDE USING gist (room_id WITH =, during WITH &&), beside the canvas showing room and booking with its id, room_id, during TSTZRANGE and status columns](https://schemity.com/images/blog/postgres-prevent-overlapping-date-ranges-exclude-vs-without-overlaps/unique-constraints-exclusion.webp)

The temporal key from `stay` to `room_rate` carries a period tag in its relation dialog, and the On delete and On update lists offer only `NO ACTION`, the one action PostgreSQL takes on a `PERIOD` key, so the diagram cannot plan a migration the database will refuse.

![Schemity's Update relation dialog for stay_room_id_nights_fkey, room_rate(room_id, valid) to stay(room_id, nights): On delete and On update both NO ACTION, Checked on each statement, and a period tag under them, over the canvas with room and booking](https://schemity.com/images/blog/postgres-prevent-overlapping-date-ranges-exclude-vs-without-overlaps/stay-relation-period.webp)

Adding an exclusion constraint to an existing table shows up in [impact analysis](https://schemity.com/doc/impact-analysis/) before it runs, with two findings: one that it "fails if overlapping rows exist" among the table's estimated rows, and one that it holds back reads and writes to `booking` while it reads them, which is the lock measured above. Converting the diagram to MySQL, SQL Server, SQLite or Snowflake drops the constraint with a note per table saying that overlapping rows are no longer refused, since none of them has an equivalent.

That matters when you design the next one: the overlap rule is part of the schema, so a reviewer looking at the booking table should see it next to the keys, and an AI agent reading the schema over MCP gets it in `get_schema` instead of guessing from the column names. How constraints the database enforces fit together in Schemity is in [check constraints and composite unique](https://schemity.com/doc/check-constraints-composite-unique/).

When a uniqueness rule should be a constraint and when an index is in [PostgreSQL unique constraint vs unique index](https://schemity.com/blog/postgres-unique-constraint-vs-unique-index/), why a nullable column lets duplicates through is in [unique constraints and nullable columns](https://schemity.com/blog/unique-constraints-and-nullable-columns/), and which timestamp type the range should be built on is in [PostgreSQL timestamp vs timestamptz](https://schemity.com/blog/postgres-timestamp-vs-timestamptz/).

## Frequently asked questions

### How do I stop two bookings of the same room from overlapping in PostgreSQL?

Install `btree_gist`, store the booked period in a range column, and declare `EXCLUDE USING gist (room_id WITH =, during WITH &&)`, or on PostgreSQL 18 and later `UNIQUE (room_id, during WITHOUT OVERLAPS)`. Both refuse a second row for the same room whose range overlaps an existing one, with `conflicting key value violates exclusion constraint`. Declare the range column `NOT NULL`, because a row with a `NULL` range passes either rule.

### Is WITHOUT OVERLAPS the same as an exclusion constraint?

Almost: the PostgreSQL manual says `UNIQUE (id, valid_at WITHOUT OVERLAPS)` behaves like `EXCLUDE USING GIST (id WITH =, valid_at WITH &&)`, and both build a GiST index. The differences are that `WITHOUT OVERLAPS` refuses empty ranges, needs at least one equality column, takes no `WHERE` clause, and is the documented target of a temporal foreign key with `PERIOD`.

### Can a temporal foreign key use `ON DELETE CASCADE`?

No. On PostgreSQL 18 and 19, a foreign key with `PERIOD` supports only `NO ACTION`; `CASCADE`, `RESTRICT`, `SET NULL` and `SET DEFAULT` are refused with `unsupported ON DELETE action for foreign key constraint using PERIOD`. The same holds for `ON UPDATE`. Deleting or shrinking a parent period that a child row still needs fails instead.
