Received: from mblox.com (unknown [213.155.153.59]) by postgresql.org (Postfix) with ESMTP id 1A480475987 for ; Wed, 10 Jul 2002 05:41:28 -0400 (EDT) Received: from salamander (salamander.mblox.com [::ffff:192.168.2.102]) (AUTH: LOGIN ian.cass) by aerosmith with esmtp; Wed, 10 Jul 2002 09:41:29 +0000 Message-ID: <064d01c227f5$a2e06180$6602a8c0@salamander> From: "Ian Cass" To: pgsql-sql@postgresql.org Subject: Help with function optimisation Date: Wed, 10 Jul 2002 10:38:36 +0100 MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit X-Priority: 3 X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook Express 6.00.2600.0000 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000 X-Archive-Number: 200207/130 X-Sequence-Number: 8509 Hi, I've got a function that I run as a trigger to update a summary table on insert to the main table. As you can see below, it does a select & an INSERT if not found, or an UPDATE if found. This currently works OK, but I'd like to improve performance by removing the SELECT & attempting an UPDATE. If it fails, I'd like to INSERT instead. Can this be done? If so, what's the syntax? CREATE FUNCTION update_summary () RETURNS opaque AS ' DECLARE result TEXT; BEGIN IF NEW.user_name NOT LIKE ''U%'' THEN SELECT into result originator FROM summary WHERE date = date_trunc(''hour'', NEW.logtime) AND client_id = NEW.client_id AND originator = NEW.originator; IF NOT FOUND THEN INSERT INTO summary (date, client_id, originator, status, total) values (date_trunc(''hour'', NEW.logtime), NEW.client_id, NEW.originator, NEW.status, ''1''); ELSE UPDATE summary SET total = total + 1 WHERE date = date_trunc(''hour'', NEW.logtime) AND client_id = NEW.client_id AND originator = NEW.originator; END IF; END IF; RETURN NEW; END; ' LANGUAGE 'plpgsql'; -- Ian Cass