I'm new to psql and triggers. I am trying to create a trigger function and a trigger such that on an update of a single column the value of that column for the rest of table should be updated. Here is an example
id | col1 | col2 |
---|---|---|
1 | text | true |
2 | text | false |
3 | text | false |
4 | text | false |
5 | text | false |
With the table above, assume that there is an update to the first row, where the value of col2 has been set to true
. I want to create a trigger function and trigger such that when there is an another update on the table, for example we set col2
for id=3
to true
, the value of col2
for id=1
should be set to false
.
Basically, what I want the trigger to do is to ensure that only one row in the entire table can have col2
set as true
CodePudding user response:
You can try a function like this:
CREATE OR REPLACE FUNCTION test_set_false()
RETURNS "pg_catalog"."trigger" AS $BODY$
DECLARE
BEGIN
if new.col2 = true then
update test_table set col2 = false where col2 = true and id != new.id;
end if;
return new;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
and call it in trigger (before update)
CREATE TRIGGER "test_set_false_update_trigger" BEFORE update ON test_table
FOR EACH ROW
EXECUTE PROCEDURE test_set_false();