views:

107

answers:

3

I need to update some rows of the tables and then display these rows. Is there a way to do this with one single query and avoid this 2 query ? :

UPDATE table SET foo=1 WHERE boo=2

SELECT * from table WHERE ( foo=1 ) AND ( boo=2 )
+1  A: 

You can use stored procedure or function. It will contains your queries.

Amber
+9  A: 

In PostgreSQL v8.2 and newer you can do this using RETURNING:

UPDATE table
SET foo=1
WHERE boo=2
RETURNING *
Mark Byers
+2  A: 

You can use a stored procedure in PL/pgSQL. Take a look at the [docs][1]

Something like this

CREATE FUNCTION run(fooVal int, booVal int) 
RETURNS TABLE(fooVal int, booVal int)
AS $$
BEGIN
  UPDATE table SET foo = fooVal WHERE boo= booVal;
  RETURN QUERY SELECT fooVal, booVal from table WHERE ( foo = fooVal ) AND ( boo = booVal );
END;
$$ LANGUAGE plpgsql;

You will save the roundtrip time for sending another statement. This should not be a performance bottleneck. So short answer: Just use two queries. That's fine and this is how you do it in SQL.

[1]: http://www.postgresql.org/docs/8.4/static/plpgsql.html docs

Janning
This is only usefull in older versions, versions before 8.2, before RETURNING was available. You don't need two queries on the same data if you can do it with just one query.
Frank Heikens
You are right, but it is a non-standard SQL feature. You should be aware of it. But i would send to queries anyway.
Janning