Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1VnAmX-0002yn-Nk for pgsql-bugs@arkaria.postgresql.org; Sun, 01 Dec 2013 17:26:09 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.80) (envelope-from ) id 1VnAmX-0008B7-2j for pgsql-bugs@arkaria.postgresql.org; Sun, 01 Dec 2013 17:26:09 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1VnAmW-0008B1-Eg for pgsql-bugs@postgresql.org; Sun, 01 Dec 2013 17:26:08 +0000 Received: from sam.nabble.com ([216.139.236.26]) by magus.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1VnAmS-0007gW-QV for pgsql-bugs@postgresql.org; Sun, 01 Dec 2013 17:26:07 +0000 Received: from [192.168.236.26] (helo=sam.nabble.com) by sam.nabble.com with esmtp (Exim 4.72) (envelope-from ) id 1VnAmP-0003CR-Kr for pgsql-bugs@postgresql.org; Sun, 01 Dec 2013 09:26:01 -0800 Date: Sun, 1 Dec 2013 09:26:01 -0800 (PST) From: David Johnston To: pgsql-bugs@postgresql.org Message-ID: <1385918761589-5781081.post@n5.nabble.com> In-Reply-To: <20131201121209.GH18793@alap2.anarazel.de> References: <20131201121209.GH18793@alap2.anarazel.de> Subject: Re: Update with subselect sometimes returns wrong result MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Pg-Spam-Score: 1.8 (+) 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 Andres Freund-3 wrote > Hi, > > On 2013-11-30 00:08:14 +0100, Oliver Seemann wrote: >> Then the following UPDATE should return exactly one row: >> >> UPDATE t1 SET id = t1.id >> FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset >> WHERE t1.id = subset.id >> RETURNING t1.id > > It turns out, this currently (as Tom points out) is a question of how > the query is planned. UPDATEs with a FROM essentially are a join between > the involved tables. Roughly, this query can either be planned as > a) Scan all rows in subset, check whether it matches a row in t1. > or > b) Scan all rows in t1, check for each whether it matches a row in subset. > > a) is perfectly fine for what you want, it will only return one row. But > b) is problematic since it will execute the subselect multiple > times, once for each row in t1. "FOR locklevel" currently has the property > of ignoring rows that the current command has modified, so you'll always > get a different row back...