Sub topic 13
Range types
This chapter assumes you can write basic SQL (SELECT, INSERT, CREATE TABLE) and can run queries in psql or another client. It also assumes you know what a constraint is. You should have read the chapters on integers and on dates and timestamps, because range types are built on top of those types.
What a range type is
A range type stores an interval of values of one underlying type as a single value. The underlying type is called the subtype. Instead of two columns, starts_at and ends_at, you store one column that holds both bounds.
PostgreSQL ships with six built-in range types:
| Range type | Subtype | Typical use |
|---|---|---|
| `int4range` | `integer` | Small numeric intervals |
| `int8range` | `bigint` | Large numeric intervals |
| `numrange` | `numeric` | Price bands, measurements |
| `daterange` | `date` | Booking periods, validity dates |
| `tsrange` | `timestamp` | Local-time intervals |
| `tstzrange` | `timestamptz` | Absolute-time intervals |
Each has a matching multirange type (for example datemultirange), which holds several non-overlapping ranges as one value. Multiranges require PostgreSQL 14 or later.
Bounds: inclusive and exclusive
Every range has a lower bound and an upper bound. Each bound is either inclusive or exclusive. The text form uses square brackets for inclusive and parentheses for exclusive:
[1,5]includes 1 and 5.(1,5)excludes both.[1,5)includes 1 and excludes 5.(1,5]excludes 1 and includes 5.
The most common choice is [), meaning inclusive lower and exclusive upper. It is also the default when you call a constructor function without a third argument. With [), adjacent ranges such as [1,5) and [5,10) touch but do not overlap, so you can tile a timeline without gaps or double counting.
A bound can be omitted to make the range unbounded on that side. [2026-01-01,) means "from 1 January 2026 onward, with no end".
Canonical form for discrete subtypes
Integers and dates are discrete: each value has a definite next value. For these subtypes PostgreSQL rewrites every range into the canonical [) form. The following query shows it:
SELECT int4range(1, 5, '[]') AS inclusive_input,
daterange('2026-01-01', '2026-01-31', '[]') AS date_input,
upper_inc(int4range(1, 5, '[]')) AS upper_inclusive;The first column displays as [1,6), because [1,5] and [1,6) contain the same integers. The second displays as [2026-01-01,2026-02-01). The third is false, because the stored upper bound is exclusive after normalization.
Continuous subtypes (numrange, tsrange, tstzrange) have no "next value", so they keep the bounds you gave them. numrange(1, 5, '[]') stays [1,5].
Constructing ranges
You can write a range as a string literal or call the constructor function named after the type. The constructor takes a lower bound, an upper bound and an optional bounds string.
SELECT '[2026-03-01,2026-03-10)'::daterange AS from_literal,
daterange('2026-03-01', '2026-03-10') AS from_function,
tstzrange('2026-03-01 09:00+00', NULL) AS open_ended,
int4range(NULL, 100) AS no_lower_bound,
'empty'::int4range AS empty_range;Passing NULL as a bound makes that side unbounded. A range where the bounds meet and exclude the point, such as int4range(5, 5), is the empty range. An empty range is a real value. It is not NULL.
A lower bound greater than the upper bound is an error:
SELECT int4range(10, 1);
-- ERROR: range lower bound must be less than or equal to range upper boundOperators and functions
The operators below work on all range types. The ones you will use most are containment, overlap and adjacency.
| Operator | Meaning | Example (true) | Column | Column |
|---|---|---|---|---|
| `@>` | range contains a value or range | `int4range(1,10) @> 5` | ||
| `<@` | value or range is contained by range | `5 <@ int4range(1,10)` | ||
| `&&` | ranges overlap | `int4range(1,5) && int4range(4,8)` | ||
| `- | -` | ranges are adjacent | `int4range(1,5) - | - int4range(5,8)` |
| `<<` | strictly left of | `int4range(1,3) << int4range(5,8)` | ||
| `>>` | strictly right of | `int4range(5,8) >> int4range(1,3)` | ||
| `+` | union (result must be contiguous) | `int4range(1,5) + int4range(5,8)` | ||
| `*` | intersection | `int4range(1,6) * int4range(4,9)` | ||
| `-` | difference | `int4range(1,10) - int4range(5,10)` |
Accessor functions return the parts of a range: lower(r), upper(r), isempty(r), lower_inc(r), upper_inc(r), lower_inf(r) and upper_inf(r). The function range_merge(a, b) returns the smallest range that covers both inputs, even when they have a gap between them.
Two details cause confusion. First, + raises an error if the union would not be contiguous. Use range_merge or a multirange when you expect a gap. Second, lower() on an unbounded range returns NULL. Check with lower_inf() if you need to tell "no bound" from "bound is NULL".
Worked example: preventing double bookings
The strongest use of ranges is an exclusion constraint. A unique constraint says "no two rows may be equal". An exclusion constraint says "no two rows may satisfy this operator on these columns". With && (overlap), it forbids overlapping ranges.
To mix a plain column such as room_id with a range in a GiST index, you need the btree_gist extension, which adds GiST operator support for scalar types.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id integer NOT NULL,
during tstzrange NOT NULL,
CONSTRAINT no_double_booking
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
INSERT INTO room_bookings (room_id, during) VALUES
(1, '[2026-05-01 09:00+00,2026-05-01 10:00+00)'),
(1, '[2026-05-01 10:00+00,2026-05-01 11:00+00)'),
(2, '[2026-05-01 09:00+00,2026-05-01 10:00+00)');
INSERT INTO room_bookings (room_id, during) VALUES
(1, '[2026-05-01 09:30+00,2026-05-01 10:30+00)');
-- ERROR: conflicting key value violates exclusion constraint "no_double_booking"The first three rows succeed. The second booking starts at 10:00, exactly when the first ends. Because the upper bound is exclusive, they do not overlap. Room 2 has the same time as room 1, but the room_id WITH = part means only rows with the same room are compared. The fourth insert overlaps the first two bookings for room 1, so the database rejects it.
Doing this with two timestamp columns and a CHECK constraint is not possible, because a CHECK sees only one row. Checking in application code is racy: two sessions can each see no conflict and both insert. The exclusion constraint is enforced by the database, so concurrent sessions cannot both succeed.
Querying and indexing ranges
A GiST index supports @>, <@, &&, -|-, << and >>. An exclusion constraint creates one automatically. For a table that needs only fast lookups, create the index yourself:
CREATE INDEX room_bookings_during_idx ON room_bookings USING gist (during);
SELECT room_id, during
FROM room_bookings
WHERE during && tstzrange('2026-05-01 09:45+00', '2026-05-01 10:15+00');A plain B-tree index on a range column supports only equality and ordering, not overlap searches. Choose GiST for the operators in the table above.
Edge cases
- Empty ranges overlap nothing.
'empty'::int4range && int4range(1,10)isfalse, and an empty range is contained by every range of the same type. An empty range therefore passes an exclusion constraint no matter what else is stored. NULLis not unbounded. ANULLrange column means "unknown". A range built with aNULLbound means "open-ended". Declare the columnNOT NULLas in the example, and use aNULLbound inside the value when you want "no end date".timestampversustimestamptz. Usetstzrangefor real events. Atsrangehas no time zone, so the same literal means different instants for different sessions.- Equality compares bounds. Two canonical discrete ranges are equal if they have the same bounds. Two continuous ranges such as
numrange(1,5,'[]')andnumrange(1,5)are different values. - Custom ranges.
CREATE TYPE ... AS RANGE (subtype = ...)defines a range over another ordered type. This is rarely needed, because the built-in six cover most cases.
When to use a range instead of two columns
Use a range when the interval is one concept and you need overlap or containment tests, or an exclusion constraint. Use two plain columns when the endpoints have separate meanings, such as shipped_at and delivered_at, or when other tools in your stack cannot read PostgreSQL range values. Many ORMs and drivers map ranges poorly, so check your client library first.
Exercise
A table price_bands has a column amount_range numrange. A row holds numrange(0, 100, '[]') and another holds numrange(100, 200, '[]'). Do these two ranges overlap, and how would you change the constructor calls so they touch without overlapping?
Show answer
They overlap, because both are inclusive and both contain the value 100, so && returns true. Use the default [) bounds: numrange(0, 100) and numrange(100, 200). Then the first excludes 100, the second includes it, && returns false and -|- returns true.
Exercise
Write a table employee_roles that stores which role an employee holds over a daterange, and prevents one employee from holding two overlapping roles. What extension do you need, and why?
Show answer
CREATE EXTENSION IF NOT EXISTS btreegist; CREATE TABLE employeeroles (employeeid integer NOT NULL, role text NOT NULL, valid daterange NOT NULL, EXCLUDE USING gist (employeeid WITH =, valid WITH &&)); The extension is needed because a GiST index has no built-in operator class for plain integers, and the constraint mixes the integer column with a range column.