Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1atkDY-0000NK-6d for pgsql-bugs@arkaria.postgresql.org; Fri, 22 Apr 2016 23:10:32 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84_2) (envelope-from ) id 1atkDX-0003rs-0p for pgsql-bugs@arkaria.postgresql.org; Fri, 22 Apr 2016 23:10:31 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1atkCt-000356-Uf for pgsql-bugs@postgresql.org; Fri, 22 Apr 2016 23:09:51 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1atkCr-00087b-BT for pgsql-bugs@postgresql.org; Fri, 22 Apr 2016 23:09:51 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id u3MN9lMe002935; Fri, 22 Apr 2016 19:09:47 -0400 From: Tom Lane To: Kevin Burke cc: pgsql-bugs@postgresql.org Subject: Re: UPDATE grabs multiple rows when it seems like it should only grab one In-reply-to: References: Comments: In-reply-to Kevin Burke message dated "Fri, 22 Apr 2016 15:56:17 -0700" Date: Fri, 22 Apr 2016 19:09:47 -0400 Message-ID: <2934.1461366587@sss.pgh.pa.us> X-Pg-Spam-Score: -2.9 (--) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-bugs Precedence: bulk Sender: pgsql-bugs-owner@postgresql.org Kevin Burke writes: > I'm trying to write a job queue that grabs one job at a time from the > queue. I expect that the following query should update a maximum of one row > in the table: > UPDATE queued_jobs > SET status='in-progress', > updated_at=now() > FROM ( > SELECT id AS inner_id > FROM queued_jobs > WHERE status='queued' > AND name = $1 > AND run_after <= now() > LIMIT 1 > FOR UPDATE > ) find_job > WHERE queued_jobs.id = find_job.inner_id > AND status='queued' I think you're assuming that the sub-query will always select the same row, but it doesn't have to. LIMIT without an ORDER BY is ill-defined. Another problem is that once the outer UPDATE has changed the status of whichever row the sub-query selects initially, that row isn't a candidate to be returned by later subquery runs, so it'd certainly move on to another row. (I'm assuming here that FOR UPDATE allows the sub-query to see the effects of the outer update immediately, which might be wrong; I lack the time to go check right now.) You might have better luck by putting the sub-query in a CTE, where it will be executed at most once. regards, tom lane -- Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-bugs