Ensure data integrity with constraints
Prevent invalid data by applying rules to your table columns using PostgreSQL constraints
Constraints reject invalid rows at insert or update time. On hypertables, TimescaleDB mirrors those rules to underlying chunks and keeps related indexes consistent when you add, change, or drop a constraint.
hypertables support all standard PostgreSQL constraint types. For foreign keys in particular, the following is supported:
- Foreign key constraints from a hypertable referencing a regular table
- Foreign key constraints from a regular table referencing a hypertable
Foreign keys from a hypertable referencing another hypertable are not supported.
For example, you can create a table that only allows positive device IDs, and non-null temperature readings. You can also check that time values for all devices are unique. To create this table, with the constraints, use this command:
CREATE TABLE conditions ( time TIMESTAMPTZ, temp FLOAT NOT NULL, device_id INTEGER CHECK (device_id > 0), location INTEGER REFERENCES locations (id), PRIMARY KEY(time, device_id)) WITH ( tsdb.hypertable);This example also references values in another locations table using a foreign
key constraint.
Time columns used for partitioning must not allow NULL values. A
NOT NULL constraint is added by default to these columns if it doesn’t already exist.
For more information on how to manage constraints, see the PostgreSQL docs.