Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jqL58-0007Ik-2H for pgsql-bugs@arkaria.postgresql.org; Tue, 30 Jun 2020 18:34:10 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1jqL56-0000Xy-Ul for pgsql-bugs@arkaria.postgresql.org; Tue, 30 Jun 2020 18:34:08 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jqL56-0000Xr-Gb for pgsql-bugs@lists.postgresql.org; Tue, 30 Jun 2020 18:34:08 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1jqL54-0000X0-EK for pgsql-bugs@lists.postgresql.org; Tue, 30 Jun 2020 18:34:07 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 05UIY5g3494166; Tue, 30 Jun 2020 14:34:05 -0400 From: Tom Lane To: jesse007@ymail.com cc: pgsql-bugs@lists.postgresql.org Subject: Re: BUG #16520: Deleting from non-existent column in CTE removes all rows In-reply-to: <16520-e4e105305f3d0c4a@postgresql.org> References: <16520-e4e105305f3d0c4a@postgresql.org> Comments: In-reply-to PG Bug reporting form message dated "Tue, 30 Jun 2020 17:30:33 -0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <494164.1593542045.1@sss.pgh.pa.us> Date: Tue, 30 Jun 2020 14:34:05 -0400 Message-ID: <494165.1593542045@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk PG Bug reporting form writes: > This will throw an error that the column does not exist: > ``` > WITH to_delete AS ( > SELECT MIN(id), username > FROM test > GROUP BY username > HAVING count(*) > 1 > ) > SELECT id > FROM to_delete; > ``` Sure, because the columns exposed by to_delete are named "min" and "username", not "id". > However, the this will not return an error and instead deletes all rows: > ``` > WITH to_delete AS ( > SELECT MIN(id), username > FROM test > GROUP BY username > HAVING count(*) > 1 > ) > DELETE FROM test > WHERE id IN ( > SELECT id > FROM to_delete > ); > ``` You've been bit by the standard SQL newbie trap that sub-selects allow outer references. That IN clause devolves to constant true (at least for non-null id values, and with to_delete known not empty), because it's just "id = id". regards, tom lane