window functions in an UPDATE - Mailing list pgsql-general

From Paul Jungwirth
Subject window functions in an UPDATE
Date
Msg-id CA+6hpakK9YTUEDsi6yJB+y7cqay83fNB7+ZJ9L7EMFv703etxw@mail.gmail.com
Whole thread Raw
List pgsql-general
Is there a trick to using window functions to SET columns in an UPDATE? Here is the query I'd like to run:

      UPDATE  profiles
      SET     score_tier = percent_rank()
                            OVER (PARTITION BY site_id ORDER BY score ASC)
      WHERE   score IS NOT NULL

But that gives me an error on Postgres 9.1:

    ERROR:  cannot use window function in UPDATE

This alternate version works, but is messier and slower:

      UPDATE  profiles p
      SET     score_tier = x.perc
      FROM    (SELECT id,
                      percent_rank() OVER (PARTITION BY site_id ORDER BY score ASC) AS perc
               FROM   profiles p2
               WHERE  score IS NOT NULL) AS x
      WHERE   p.id = x.id
      AND     p.score IS NOT NULL

That second version is also prone to deadlocks if another job is updating the profiles table at the same time, even with a query like this:

    UPDATE "profiles" SET "updated_at" = '2012-11-13 21:53:23.840976' WHERE "profiles"."id" = 219474

Is there any way to reformulate this query so it is cleaner, faster, and not prone to deadlocks?

Thanks,
Paul

--
_________________________________
Pulchritudo splendor veritatis.

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: Running out of memory while making a join
Next
From: Craig Ringer
Date:
Subject: Re: general fear question about move PGDATA from one Disc to another