Re: delete statement returning too many results

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Ron <ronljohnsonjr(at)gmail(dot)com>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: delete statement returning too many results
Date: 2022-11-28 14:34:45
Message-ID: CAKFQuwa3qYG1B-1BqRrS4L+aV0hqhjWGy4md6o_y+8qixzUJUA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Nov 28, 2022 at 7:18 AM Ron <ronljohnsonjr(at)gmail(dot)com> wrote:

> On 11/28/22 07:29, Arlo Louis O'Keeffe wrote:
> > Hello everyone,
> >
> > I am seeing weird behaviour of a delete statement that is returning more
> results than I am expecting.
> >
> > This is the query:
> >
> > DELETE FROM queue
> > WHERE
> > id IN (
> > SELECT id
> > FROM queue
> > ORDER BY id
> > LIMIT 1
> > FOR UPDATE
> > SKIP LOCKED
> > )
> > RETURNING *;
> >
> > My understanding is that the limit in the sub-select should prevent this
> query from ever
> > returning more than one result. Sadly I am seeing cases where there is
> more than one result.
> >
> > This repository has a Java setup that pretty reliably reproduces my
> issue:
> > https://github.com/ArloL/postgres-query-error-demo
> >
> > I checked the docs for select and delete and couldn’t find any hint for
> cases
> > where the behaviour of limit might be surprising.
> >
> > Am I missing something?
>
> More than one row will be deleted if there in more than one record in
> "queue" for the specific value of "id" (i.e "id" is not unique).
>
>
Given that the example code provided has "ID" as a PK on the queue table
this fact, while true, is unhelpful for this specific question.

There is a nice big caution regarding the default read committed isolation
mode, order by, and for update, in the documentation, but I cannot work out
exactly why this example seems to be triggering it.

https://www.postgresql.org/docs/current/sql-select.html

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2022-11-28 17:11:53 Re: delete statement returning too many results
Previous Message yin.zhb@163.com 2022-11-28 14:20:35 Re: Re: how to implement add using upsert and trigger?