Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1eWOPB-00089R-3D for pgsql-general@arkaria.postgresql.org; Tue, 02 Jan 2018 15:23:05 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1eWOPA-00020m-Ng for pgsql-general@arkaria.postgresql.org; Tue, 02 Jan 2018 15:23:04 +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 1eWOPA-00020c-Fz for pgsql-general@lists.postgresql.org; Tue, 02 Jan 2018 15:23:04 +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.89) (envelope-from ) id 1eWOP8-0003H6-4H for pgsql-general@postgresql.org; Tue, 02 Jan 2018 15:23:04 +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 w02FN0Vg032467; Tue, 2 Jan 2018 10:23:00 -0500 From: Tom Lane To: Jeff Janes cc: Durumdara , Postgres General Subject: Re: Select for update / deadlock possibility? In-reply-to: References: Comments: In-reply-to Jeff Janes message dated "Tue, 02 Jan 2018 09:02:50 -0500" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <32465.1514906580.1@sss.pgh.pa.us> Date: Tue, 02 Jan 2018 10:23:00 -0500 Message-ID: <32466.1514906580@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Jeff Janes writes: > On Tue, Jan 2, 2018 at 3:22 AM, Durumdara wrote: >> Is "select for update" atomic (as transactions) or it isn't? > It is atomic, but you do have to worry about deadlocks. I think by "atomic" the OP intends "all the row locks are magically acquired at the same instant". Which they aren't, they're taken one at a time. So if you have different transactions trying to lock overlapping sets of rows, there's a risk of deadlock. Which will be detected and one transaction will fail, but still you might wish to avoid that. The usual rule for that is "be sure all transactions acquire locks in the same order". So just throw an "order by id" type of clause into the SELECT FOR UPDATE, and you should be fine. Personally, I'd still code the application to retry on deadlock failures, just for robustness. regards, tom lane