Ask Your Question
2

Is it possible to create a trigger in Postgresql that only allows updates for a selected column while preventing updates for all other columns?

asked 2022-02-16 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-02-27 12:00:00 +0000

pufferfish gravatar image

Yes, it is possible to create a trigger in PostgreSQL that only allows updates for a selected column while preventing updates for all other columns.

You can use a BEFORE UPDATE trigger to achieve this. Within the trigger function, you can check if the column being updated is the allowed column. If it is, you can allow the update to proceed. If it is not, you can raise an exception to prevent the update.

Here's an example of how to create such a trigger:

CREATE OR REPLACE FUNCTION only_allow_update_to_selected_column()
RETURNS TRIGGER AS $$
BEGIN
  IF TG_OP = 'UPDATE' AND NEW.selected_column <> OLD.selected_column THEN
    RAISE EXCEPTION 'Updates to columns other than selected_column are not allowed';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER only_allow_update_trigger
BEFORE UPDATE ON your_table
FOR EACH ROW
EXECUTE FUNCTION only_allow_update_to_selected_column();

Replace your_table with the name of your table, and selected_column with the name of the column you want to allow updates to.

With this trigger in place, any attempt to update a column other than selected_column will result in an exception being raised and the update being prevented.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-16 11:00:00 +0000

Seen: 15 times

Last updated: Feb 27 '23