I have the following UPDATE statement:
update mytable
set a = first_part(genid()),
b = second_part(genid()),
c = third_path(genid())
where package_id = 10;
In this example the function genid() is called three times for each row, which is wrong – I want it to be called only once for each row of mytable.
I’m using PostgreSQL 8.4 database. How to write the correct update?
I’ve tried something like this:
update mytable
set a = first_part(g),
b = second_part(g),
c = third_path(g)
where package_id = 10
from genid() as g;
But it didn’t work, because genid() has been called only once for the whole update statement.
Have you tried Postgres’ non-standard
UPDATE .. FROMclause? I imagine, this would workNote that I’m forcing
genid()to be called exactly once per record inmytablewithin the subselect. Then I’m self-joiningmytableandgenusing a hypotheticalidcolumn.See the documentation here:
http://www.postgresql.org/docs/current/interactive/sql-update.html
This seems to have been introduced with Postgres 9.0 only, though.If that seems too complicated (i.e. not very readable), you can still resort to pgplsql as user Florin suggested here.