Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1bZgYS-0002Jt-Vw for pgsql-docs@arkaria.postgresql.org; Tue, 16 Aug 2016 15:45:29 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84_2) (envelope-from ) id 1bZgYS-0006j3-Ij for pgsql-docs@arkaria.postgresql.org; Tue, 16 Aug 2016 15:45:28 +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 1bZgYS-0006hz-13 for pgsql-docs@postgresql.org; Tue, 16 Aug 2016 15:45:28 +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 1bZgY8-0000ZG-Og for pgsql-docs@postgresql.org; Tue, 16 Aug 2016 15:45:27 +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 u7GFirxT012785; Tue, 16 Aug 2016 11:44:54 -0400 From: Tom Lane To: xrg@linux.gr cc: pgsql-docs@postgresql.org Subject: Re: Row locking within a SELECT statement In-reply-to: <20160816061952.30234.45751@wrigleys.postgresql.org> References: <20160816061952.30234.45751@wrigleys.postgresql.org> Comments: In-reply-to xrg@linux.gr message dated "Tue, 16 Aug 2016 06:19:52 -0000" Date: Tue, 16 Aug 2016 11:44:53 -0400 Message-ID: <12784.1471362293@sss.pgh.pa.us> X-Pg-Spam-Score: -2.5 (--) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-docs Precedence: bulk Sender: pgsql-docs-owner@postgresql.org xrg@linux.gr writes: > In order to avoid concurrent manipulation of rows, I do issue a "SELECT .. > FOR UPDATE" on the sets of rows, before UPDATEing them (because UPDATEs > cannot be ordered). > transaction A { > SELECT .. FROM alerts WHERE <clauseA> FOR UPDATE; > ... decide ... > UPDATE alerts ... > } > transaction B { > SELECT .. FROM alerts WHERE <clauseB> 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 -- Sent via pgsql-docs mailing list (pgsql-docs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-docs