pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Ian Cass <ian.cass@mblox.com>
To: pgsql-sql@postgresql.org
Subject: Help with function optimisation
Date: Wed, 10 Jul 2002 10:38:36 +0100
Message-ID: <064d01c227f5$a2e06180$6602a8c0@salamander> (raw)

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




view thread (2+ messages)  latest in thread

Message-ID: <064d01c227f5$a2e06180$6602a8c0@salamander>
Permalink:  ../064d01c227f5$a2e06180$6602a8c0@salamander/
Also on:    postgresql.org/message-id/064d01c227f5$a2e06180$6602a8c0@salamander

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: ian.cass@mblox.com
  Subject: Re: Help with function optimisation
  In-Reply-To: <064d01c227f5$a2e06180$6602a8c0@salamander>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox