Below is the code I am using in a PostgreSQL 16 database. Every time I try to update the salary I get:
ERROR: infinite recursion detected in rules for relation "employees"
SQL state: 42P17"
Object used
create table rowan.employees (emp_id serial primary key, name varchar(100), salary numeric);
Inserting values
insert into rowan.employees (name, salary) values
('John Doe', 50000),
('Jane Doe', 60000),
('Rafael Orta',80000);
Creation of the rule
create or replace rule update_salary
as on update to rowan.employees
where new.salary > 70000
and pg_trigger_depth() = 0
do instead
update rowan.employees
set salary = 70000
where emp_id = new.emp_id;
Performing the Update
update rowan.employees set salary = 80000 where emp_id = 3;
Checking the values
select * from rowan.employees;
I am trying to do the command below:
update rowan.employees set salary = 80000 where emp_id = 3;
I was expecting for it to update the salary to be 70000.
2
Answers
You might want to use a trigger for this like the following (untested):
Invoking the rule system is a problem as it rewrites the query first before anything is executed. The
WHERE
condition would be part of the rewritten query – but it still includes anUPDATE
onrowan.employees
, i.e. the rule is executed again – and again and again. Note that theWHERE
will be incorporated in the rewritten query and not checked before rewriting the query (this includes that allUPDATE
queries will be rewritten, doesn’t matter if the condition is fulfilled).Listen to the comments and use triggers instead of rules.
If you want to use a rule then a simple example:
Basically create a view over the table and use
do instead
against the view with theinstead
acting against the table. That will deal with the recursion issue.