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.
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
Asked: 2022-02-16 11:00:00 +0000
Seen: 15 times
Last updated: Feb 27 '23
What is the procedure for using pg_restore on Windows with Docker?
Due to SyntaxError, why am I unable to create a TIMESTAMP WITH TIMEZONE column in postgres?
What are the benefits of choosing sqlalchemy.types instead of sqlalchemy.dialects.mssql?
What is the method for placing parentheses in column names when creating a table using an SQL query?
How can larger BLOBs be compressed without being inlined?
How can pgcrypto be used to secure data on Postgres?
How can you apply a filter using in_() in SQLAlchemy for JSON data?