Automate tasks with triggers
Use PostgreSQL triggers to automatically execute functions when data changes occur in TimescaleDB hypertables
TimescaleDB supports PostgreSQL triggers on a hypertable the same way you use them on a regular table. When you create, alter, drop, enable, or disable a trigger on a hypertable — including via ALTER TABLE … ENABLE/DISABLE TRIGGER with the ALL, USER, ALWAYS, and REPLICA variants — TimescaleDB propagates the change to every chunk.
Create a trigger
Section titled “Create a trigger”This example creates a new table called error_conditions with the same schema
as conditions, but that only stores records which are considered errors. An
error, in this case, is when an application sends a temperature or humidity
reading with a value that is greater than or equal to 1000.
- Create a function that inserts erroneous data into the
error_conditionstableCREATE OR REPLACE FUNCTION record_error()RETURNS trigger AS $record_error$BEGINIF NEW.temperature >= 1000 OR NEW.humidity >= 1000 THENINSERT INTO error_conditionsVALUES(NEW.time, NEW.location, NEW.temperature, NEW.humidity);END IF;RETURN NEW;END;$record_error$ LANGUAGE plpgsql; - Create a trigger that calls this function whenever a new row is inserted into the hypertableCREATE TRIGGER record_errorBEFORE INSERT ON conditionsFOR EACH ROWEXECUTE FUNCTION record_error();
- Verify that error rows are captured
All data is inserted into the
conditionstable, but rows that contain errors are also added to theerror_conditionstable.
For all supported trigger types and clauses, see the PostgreSQL CREATE TRIGGER docs.
Limitations
Section titled “Limitations”- Triggers are not supported on continuous aggregates.
ROW-level triggers with transition tables are not supported on hypertables.DELETEtriggers with transition tables are not supported.