Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id D2A891337BC8 for ; Mon, 9 May 2011 09:38:32 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 73552-04 for ; Mon, 9 May 2011 12:38:15 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from zebedee.cranntara.net (zebedee.cranntara.net [91.186.7.79]) by mail.postgresql.org (Postfix) with ESMTP id 8B6961337B8B for ; Mon, 9 May 2011 09:38:13 -0300 (ADT) Received: from [88.210.188.180] (helo=bolek.coachhouse) by zebedee.cranntara.net with esmtpsa (TLS1.0:RSA_AES_256_CBC_SHA1:32) (Exim 4.72) (envelope-from ) id 1QJPiz-0005UL-AV for pgsql-sql@postgresql.org; Mon, 09 May 2011 13:38:12 +0100 Received: from dick.coachhouse ([192.168.1.32] ident=tarlika) by bolek.coachhouse with esmtp (Exim 4.69) (envelope-from ) id 1QJPOw-00062Z-OJ for pgsql-sql@postgresql.org; Mon, 09 May 2011 13:17:26 +0100 Date: Mon, 9 May 2011 13:17:17 +0100 From: Tarlika Elisabeth Schmitz To: pgsql-sql@postgresql.org Subject: Trigger: update if record exists Message-ID: <20110509131717.1370e36f@dick.coachhouse> X-Mailer: Claws Mail 3.5.0 (GTK+ 2.12.12; i486-pc-linux-gnu) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.9 tagged_above=-5 required=5 tests=BAYES_00=-1.9 X-Spam-Level: X-Archive-Number: 201105/49 X-Sequence-Number: 35333 I wrote a trigger function to convert inserts into updates if the record exists already. - I am not using rules because the table is populated via COPY. - I am employing a two-stage process (PERFORM, then UPDATE) because the update trigger might decide not to update after all, and therefore FOUND cannot be used to indicate the record's existence. Is this the most efficient way to code this trigger? ====================== System: Postgresql 8.3 ====================== Code: ---------------------- CREATE OR REPLACE insert_existing() RETURNS trigger AS $$ BEGIN PERFORM 1 FROM zhorse WHERE id = NEW.id; IF NOT FOUND THEN RETURN NEW; ELSE UPDATE tbl SET (c1, c2, c3, ...) = (NEW.c1, NEW.c2, NEW.c3, ...) WHERE id = NEW.id; RETURN NULL; END IF; END $$ LANGUAGE plpgsql; CREATE TRIGGER a_insert_existing BEFORE INSERT ON tbl FOR EACH ROW EXECUTE PROCEDURE insert_existing();