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 1paHmF-0003q8-9G for pgsql-bugs@arkaria.postgresql.org; Thu, 09 Mar 2023 15:01:55 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1paHmD-0000hd-EG for pgsql-bugs@arkaria.postgresql.org; Thu, 09 Mar 2023 15:01:53 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1paHmD-0000hU-6W for pgsql-bugs@lists.postgresql.org; Thu, 09 Mar 2023 15:01:53 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1paHmA-0003Qm-Mg for pgsql-bugs@lists.postgresql.org; Thu, 09 Mar 2023 15:01:52 +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 329F1m7i377749; Thu, 9 Mar 2023 10:01:48 -0500 From: Tom Lane To: hyanchurevich@spotware.com cc: pgsql-bugs@lists.postgresql.org Subject: Re: BUG #17827: Rule on insert into table doesn't work when excepting select from the table itself In-reply-to: <17827-1dfd5ad9af280484@postgresql.org> References: <17827-1dfd5ad9af280484@postgresql.org> Comments: In-reply-to PG Bug reporting form message dated "Thu, 09 Mar 2023 10:27:00 +0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <377747.1678374108.1@sss.pgh.pa.us> Date: Thu, 09 Mar 2023 10:01:48 -0500 Message-ID: <377748.1678374108@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk PG Bug reporting form writes: > create table tbl (id int); > create table rule_stat (msg text, id int); > create rule rule_tbl as on insert to tbl do insert into rule_stat > values('Rule triggered for ',new.id); > insert into tbl > select 1 > except > select id from tbl; > table rule_stat; -- no rows This is not a bug. The DO ALSO command executes after the original INSERT command, and what it executes looks basically like insert into rule_stat select 'Rule triggered for ', id from (select 1 except select id from tbl); But at this point we've already completed the original INSERT, so now there is a row with id 1 in "tbl", and thus the EXCEPT produces nothing. While there are use-cases for this sort of behavior, most people find that propagating data to another table is better done with an AFTER trigger. It's far easier to understand what will happen. regards, tom lane