My table has two columns:
startsAt
endsAt
Both hold date and time. I want to make following constraint:
IF both columns are NOT NULL then range between startsAt and endsAt must not overlap with other ranges (from other rows).
The syntax for creating a unique constraint using an ALTER TABLE statement in PostgreSQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.
To find the name of a constraint in PostgreSQL, use the view pg_constraint in the pg_catalog schema. Join the view pg_catalog. pg_constraint with the view pg_class ( JOIN pg_class t ON t. oid = c.
In PostgreSQL, the UNIQUE CONSTRAINT is used to maintain the individuality of the values that we store into a field or a column of the table. It is compatible with a group of column constraints or column constraints and a table constraint.
PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.
You can keep your separate timestamp
columns and still use an exclusion constraint on an expression:
CREATE TABLE tbl (
tbl_id serial PRIMARY KEY
, starts_at timestamp
, ends_at timestamp
, EXCLUDE USING gist (tsrange(starts_at, ends_at) WITH &&) -- no overlap
);
Constructing a tsrange
value without explicit bounds as tsrange(starts_at, ends_at)
assumes default bounds: inclusive lower and exclusive upper - '[)'
, which is typically best.
db<>fiddle here
Old sqlfiddle
Related:
ALTER TABLE tbl ADD CONSTRAINT tbl_no_overlapping_time_ranges
EXCLUDE USING gist (tsrange(starts_at, ends_at) WITH &&)
Syntax details are the same as for CREATE TABLE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With