Re: Delete from locking ordering differences

From: Rob Sargent <robjsargent(at)gmail(dot)com>
To: pgsql-sql(at)lists(dot)postgresql(dot)org
Subject: Re: Delete from locking ordering differences
Date: 2022-09-23 16:04:56
Message-ID: 7b30c39f-2d36-e540-7494-c41b7e8b7179@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 9/23/22 01:31, Peter Hendriks wrote:
> We are wondering if anyone can explain the difference we are having in
> production with the following queries:
>
> DELETE FROM store
> WHERE id IN (
>   SELECT id FROM store
>   FOR UPDATE SKIP LOCKED
>   ORDER BY ID
>   LIMIT 1000
> )
> RETURNING id, payload
>
> This query is sometimes executed with high concurrency, and then can
> hang indefinitely, we assume because of a locking problem that
> postgresql is not detecting as a deadlock.
>
> This alternative query does not have the hanging problem:
>
> WITH store_ids AS (
>   SELECT id FROM store
>   FOR UPDATE SKIP LOCKED
>   ORDER BY ID
>   LIMIT 1000
> )
> DELETE FROM store s
> USING store_ids si
> WHERE s.id <http://s.id> = si.id <http://si.id>
> RETURNING s.id <http://s.id>, s.payload
>
> Can anyone explain why the first query is expected to fail (hang), and
> the second query does not have this problem? We would be interested in
> more understanding on this. Thanks!

The "optimizatin fence" nature of CTEs appears to be a win in this
case.  Why the "order by"?  I assume these are down within a transaction?

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Peter Hendriks 2022-09-29 13:51:31 Re: Delete from locking ordering differences
Previous Message Peter Hendriks 2022-09-23 07:31:17 Delete from locking ordering differences