Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.