Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1TZ2s0-0008JX-0p for pgsql-bugs@postgresql.org; Thu, 15 Nov 2012 17:04:52 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1TZ2ry-00076k-8m for pgsql-bugs@postgresql.org; Thu, 15 Nov 2012 17:04:51 +0000 Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.5/8.14.5) with ESMTP id qAFH4mm8017775; Thu, 15 Nov 2012 12:04:48 -0500 (EST) From: Tom Lane To: mtesfaye@gmail.com cc: pgsql-bugs@postgresql.org Subject: Re: BUG #7662: INSERT rule doesn't work as expected In-reply-to: References: Comments: In-reply-to mtesfaye@gmail.com message dated "Thu, 15 Nov 2012 16:48:34 +0000" Date: Thu, 15 Nov 2012 12:04:48 -0500 Message-ID: <17774.1352999088@sss.pgh.pa.us> X-Pg-Spam-Score: -2.0 (--) X-Archive-Number: 201211/80 X-Sequence-Number: 34638 mtesfaye@gmail.com writes: > ON INSERT RULE doesn't always work as expected. > The reasoning for this particular rule was to add the new value to an > existing value if it is determined that the key already exists. > CREATE OR REPLACE RULE "dup_add_test_r_rule" AS > ON INSERT TO test_r > WHERE > EXISTS(SELECT 1 FROM test_r a WHERE a.id=NEW.id) > DO INSTEAD > (UPDATE test_r a SET val=a.val+NEW.val WHERE a.id=NEW.id); Per the manual: For ON INSERT rules, the original query (if not suppressed by INSTEAD) is done before any actions added by rules. This allows the actions to see the inserted row(s). So the behavior in your example is (1) The EXISTS test fails, so the INSERT is allowed to execute. (2) Now the EXISTS test passes, so the UPDATE is allowed to execute. This might not be what you wished would happen, but it's not a bug; it's the way rules are defined to work. You might have better luck with a BEFORE INSERT trigger. regards, tom lane