AI Hints
Home›PostgreSQL Tutorial›Enums, UUIDs and Ranges
PostgreSQL · Lesson 48 of 120

Range Types

From and to.

⏱ 2 min read▶ Video at 41:53🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A meeting room is booked from two to three. Can someone else book two thirty to four? Ranges store a from and a to as one value, and Postgres can stop overlaps.

  • 2:00 to 3:00
  • 2:30 to 4:00?
  • No overlaps

No double bookings

During is a time range. The exclude constraint refuses two bookings for the same room whose ranges overlap. It needs the btree gist extension. Run it. The overlapping booking is rejected.

query.sqlsql
CREATE EXTENSION btree_gist;
CREATE TABLE room_bookings (
  room   text,
  during tstzrange,
  EXCLUDE USING gist (room WITH =, during WITH &&)
);
INSERT INTO room_bookings VALUES ('Reading Room', '[2026-03-14 14:00+00, 2026-03-14 15:00+00)');
INSERT INTO room_bookings VALUES ('Reading Room', '[2026-03-14 14:30+00, 2026-03-14 16:00+00)');
Output
CREATE EXTENSION
CREATE TABLE
INSERT 0 1
ERROR:  conflicting key value violates exclusion constraint
"room_bookings_room_during_excl"
DETAIL:  Key (room, during)=(Reading Room, ["2026-03-14 14:30:00+00","2026-03-14
16:00:00+00")) conflicts with existing key (room, during)=(Reading Room, ["2026-03-14
14:00:00+00","2026-03-14 15:00:00+00")).
Also uses _empty
1

Range types

Int range and num range hold numbers. Date range holds days, and t s t z range holds moments. Square brackets include the edge, round ones exclude it. And double ampersand means overlaps.

keyvalue
int4range, numrangenumbers
daterangedays
tstzrangemoments
[ ) and &&edges, overlap

Summary

Ranges store from and to as one value, and exclusion constraints prevent overlaps. Next, how indexes work.

Key takeaways
  • tstzrange
  • &&
  • EXCLUDE
Next up: How Indexes Work — find rows fast