I have 2 tables in PostgreSQL-12, SENSORS (receives timeseries data feed from sensors) and LABELS (contains sensor labels & meta-data). I am trying to create a PostgreSQL trigger to update the sensor data as they are inserted into SENSORS. Each row of sensor data will be updated with the corresponding label name from LABELS. Unable to get the row update to work. Sample shown below:
Sample Dataset
CREATE TABLE sensor (
datavalue integer,
created timestamp,
label_id integer,
label_name text);
CREATE TABLE labels (
id integer,
label_id integer,
label_name text);
Insert into labels values (1, 215, 'Home'), (2, 216, 'Shop'), (3, 217, 'Flat'), (4, 218, 'Street');
Insert into sensor values (67, '2020-09-02 08:40:07.354', 215),(67, '2020-09-02 08:41:07.354', 215),(67, '2020-09-02 08:41:07.354', 216);
Trigger Function
CREATE OR REPLACE FUNCTION update_name()
RETURNS trigger AS
$func$
BEGIN
UPDATE sensor
SET label_name = b.label_name
from labels b
where new.label_id = b.label_id;
RETURN NEW;
END
$func$ LANGUAGE plpgsql;
CREATE TRIGGER name_update_trigger
AFTER INSERT OR UPDATE ON sensor
FOR EACH ROW EXECUTE PROCEDURE update_name();
Test row insertion
Insert into sensor values (78, '2020-09-02 08:40:07.354', 215),(77, '2020-09-02 08:41:07.354', 215),(67, '2020-09-02 08:41:07.354', 216);
I have a very large number of rows flowing in, and would like to update each row as it is inserted.
Any assistance greatly appreciated. Thanks!
SELECT * FROM sensor s INNER JOIN labels b ON b.label_id = s.label_id
or similar. Alternatively you could do such update in batch to update them masivelly.