postgres: materializing updates

  • Thread starter Deleted member 43669
  • Start date
Status
Not open for further replies.
D

Deleted member 43669

Guest
Hi all,

Just found out today that if you do:

Code:
update foo
set bar = (
select {complex_expr} new_bar
from {some_tables}
where {complex_join}
and foo.id = {some_table}.id)
where {condition_goes_here}

in Postgres (i.e. complex update based on a select), it tends to be slllllllow. Fortunately, if you replace it with:

Code:
begin;

create temporary table tmp_table on commit drop as (
select {some_table}.id, {complex_expr} new_bar
from {some_tables}
where {complex_join}
);

update foo
set bar = (
select new_bar
from tmp_table
where foo.id = tmp_table.id)
where {condition_goes_here};

commit;

It flies.

Should I use Postgres' non-standard FROM in the UPDATE? Is this a flaw of the optimizer? Other thoughts?

(I use the temp table because it's quick and I have several updates to perform which can reuse some temp tables...)
 
Looks like a correlated subquery. In other words, the subquery is executed once for each row in foo that you are updating. This is probably less than ideal even in your second example.

I think you should use the non-standard syntax unless you have a good reason to avoid it. newwb has the right idea, though Postgres does not support JOIN syntax in UPDATE statements. You can however specify a FROM list and include your join condition in the WHERE clause.

UPDATE foo f
SET bar = tt.new_bar
FROM tmp_table tt
WHERE f.id = tt.id
AND {condition_goes_here};


Also, if you are ever wondering what the query planner is doing:

http://www.postgresql.org/docs/9.0/inte ... plain.html
http://www.postgresql.org/docs/9.0/inte ... plain.html
 
Status
Not open for further replies.