Re: Row locking within a SELECT statement

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: xrg(at)linux(dot)gr
Cc: pgsql-docs(at)postgresql(dot)org
Subject: Re: Row locking within a SELECT statement
Date: 2016-08-16 15:44:53
Message-ID: 12784.1471362293@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-docs

xrg(at)linux(dot)gr writes:
> In order to avoid concurrent manipulation of rows, I do issue a &quot;SELECT ..
> FOR UPDATE&quot; on the sets of rows, before UPDATEing them (because UPDATEs
> cannot be ordered).

> transaction A {
> SELECT .. FROM alerts WHERE &lt;clauseA&gt; FOR UPDATE;
> ... decide ...
> UPDATE alerts ...
> }

> transaction B {
> SELECT .. FROM alerts WHERE &lt;clauseB&gt; FOR UPDATE;
> ... decide, sort, filter ...
> UPDATE / DELETE alerts
> }

> Still, those 2 transactions *do* deadlock.

It's hard to comment on that without any specifics. My first guess is
that clauseA and clauseB are sufficiently different that different plan
types are chosen for the two SELECTs, and those plans visit (some of)
the same rows in different orders, leading to deadlock in their row lock
acquisition attempts. You could probably alleviate that by using
ORDER BY in the SELECTs; but read the "The Locking Clause" section of the
SELECT reference page for some caveats about combining ORDER BY with
FOR UPDATE.

regards, tom lane

In response to

Browse pgsql-docs by date

  From Date Subject
Next Message Alexander Law 2016-08-16 16:02:41 Several repeated words
Previous Message Tom Lane 2016-08-16 14:59:55 Re: Outdated sentence in the pg_am description