tags:

views:

30

answers:

2

I'm trying to use PostgreSQL's RETURNING clause on an UPDATE within in UPDATE statement, and running into trouble.

Postgres allows a query clause in an INSERT, for example:

INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';

I would like to use the RETURNING clause from an UPDATE as the query clause for an INSERT, for example:

INSERT INTO user_status_history(status) UPDATE user_status SET status = 'ACTIVE' WHERE status = 'DISABLED' RETURNING status

All of the Postgres references I can find suggest that a RETURNING clause behaved exactly like a SELECT clause, however when I run something like the above, I get the following:

ERROR: syntax error at or near "UPDATE" LINE 2: UPDATE user_statuses

Despite being able to execute the UPDATE portion of the above query without error.

Is using the RETURNING clause from an UPDATE as the query clause for an INSERT's query clause possible?

The goal is to update one table and insert into another with a single query, if possible.

A: 

I think this is not possible the way you are trying to do. I'd suggest you to write an AFTER UPDATE trigger, which could perform the insert, then.

pcent
A: 

Right now, no.

There was a feature that almost made it into PostgreSQL 9.0 known as Writeable CTE's that does what you're thinking (although the syntax is different).

Currently, you could either do this via a trigger or as two separate statements.

rfusca