if exists select ... in plpgsql code

From: Roland Roberts <roland(at)astrofoto(dot)org>
To: pgsql-general(at)postgresql(dot)org
Subject: if exists select ... in plpgsql code
Date: 2002-09-11 03:55:40
Message-ID: m2hegxdvsz.fsf@kuiper.rlent.pnet
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I'm trying to write a trigger that enforces a constraint which can't
be done via an index. Namely, I have 4 columns which, in combination,
should be unique. Two of those columns can have null entries in which
case, the row with the null entry should be unique when considering
the other non-null parts.

I'm running into a couple of problems. The plpgsql parser doesn't
seem to like my trigger function since it keeps complaining when it
tries to compile it. In order to debug, I simplified the trigger to
the following:

create function deepsky_nodups() returns opaque as '
begin
if (NEW.suffix is NULL and NEW.component is NULL) then
if (exists select id from deepsky where catalog = NEW.catalog and entry = NEW.entry and suffix is null and component is null) then
return NULL;
end if;
end if;
end;
' language 'plpgsql';

where the table deepsky is defined as

create table deepsky (
id serial primary key,
catalog varchar (10) not null,
entry varchar (30) not null,
suffix varchar (1), -- NGC/IC catalogues use this
component varchar (1), -- NGC/IC catalogues use this
status varchar (2),
mag_p numeric (6,2),
type varchar (10),
surface_brightness numeric (6,2),
constellation varchar (3),
ra numeric,
decl numeric,
epoch varchar (10),
diameter numeric (8,2),
diameter_b numeric (8,2),
position_angle numeric (6,2),
remark text
);

postgresql doesn't like the "if (exists select id from ...)".

How do I need to form this query to check for an existing entry?

roland
--
PGP Key ID: 66 BC 3B CD
Roland B. Roberts, PhD RL Enterprises
roland(at)rlenter(dot)com 76-15 113th Street, Apt 3B
roland(at)astrofoto(dot)org Forest Hills, NY 11375

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2002-09-11 04:37:47 Re: if exists select ... in plpgsql code
Previous Message Tom Lane 2002-09-11 03:41:08 Re: Psql regex is NFA or DFA?