Received: from maia.hub.org (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id D40A56326F9 for ; Thu, 25 Feb 2010 11:19:55 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 55415-08 for ; Thu, 25 Feb 2010 15:19:34 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from out07.wanadoo.es (out07.wanadoo.es [62.36.20.207]) by mail.postgresql.org (Postfix) with ESMTP id 0CE66633156 for ; Thu, 25 Feb 2010 11:19:35 -0400 (AST) Received: from [83.44.109.142] (helo=hilex11.localnet) by out07.wanadoo.es with esmtpa (Exim 4.43) id 1NkfUw-0006d2-4C for pgsql-sql@postgresql.org; Thu, 25 Feb 2010 16:19:30 +0100 From: Aron To: pgsql-sql@postgresql.org Subject: Using new.id in the WHERE condition of one UPDATE inside ON INSERT rule Date: Thu, 25 Feb 2010 16:19:32 +0100 User-Agent: KMail/1.12.2 (Linux/2.6.31-19-generic; KDE/4.3.2; x86_64; ; ) MIME-Version: 1.0 Content-Type: Text/Plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Message-Id: <201002251619.32048.auryn@wanadoo.es> X-login: X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-0.185 tagged_above=-10 required=5 tests=BAYES_40=-0.185 X-Spam-Level: X-Archive-Number: 201002/94 X-Sequence-Number: 33693 I would like to avoid using "SELECT MAX(id) FROM my_table" (it doesn't seem a good method), but if I use "new.id", I get new id values, not the "id" inserted with the rule, and the condition is always false. Complete example (it works because it doesn't use new.id inside condition): DROP TABLE IF EXISTS my_table; DROP TABLE IF EXISTS my_other_table; CREATE TABLE my_other_table ( id serial PRIMARY KEY, my_other_cost INTEGER ); INSERT INTO my_other_table(my_other_cost) VALUES(155); INSERT INTO my_other_table(my_other_cost) VALUES(277); CREATE TABLE my_table ( id serial PRIMARY KEY, id_other INTEGER, my_cost INTEGER ); CREATE OR REPLACE RULE my_insert AS ON INSERT TO my_table DO ALSO UPDATE my_table SET my_cost = my_other_table.my_other_cost FROM my_other_table WHERE new.id_other = my_other_table.id AND my_table.id = (SELECT MAX(id) FROM my_table); -- I want " = new.id" here, but doesn't work as I expect INSERT INTO my_table(id_other) VALUES(1); INSERT INTO my_table(id_other) VALUES(2); SELECT * FROM my_table; Thanks --