Girders Blog
Notes on building internet applications

Updating a PostgreSQL view

Jan 5, 2009

In PostgreSQL (8.2), we can create a view to access a join of two tables.

create view join_view as SELECT p.id, p.group, c.parent_id, c.status FROM child c JOIN parent p ON c.parent_id = p.id ;

Now we can do

select * from join_view where group = 1;

However, if we try to update the view, we can not.

update join_view set status=4 where group=1;
ERROR:  cannot update a view
HINT:  You need an unconditional ON UPDATE DO INSTEAD rule.

So we need to create this rule to execute this trigger-like command

create rule join_view_update as on update to join_view do instead (update child set status=NEW.status where id=NEW.id and parent_id=NEW.parent_id );

Now we can execute the update!

update join_view set status=4 where group=1;
UPDATE 1
select * from join_view where group = 1;

And see the results!

Note: I changed internal conditions and naming, and hope I have no inadvertently mis-typed something. Apologies in advance if this had a simple syntax error.