Re: UNIQUEness and time interval

From: Rodrigo De León <rdeleonp(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: UNIQUEness and time interval
Date: 2007-10-08 14:46:40
Message-ID: 1191854800.465075.65670@y42g2000hsy.googlegroups.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Oct 4, 4:45 am, Nicolas Boullis <nicolas(dot)boul(dot)(dot)(dot)(at)ecp(dot)fr> wrote:
> I'd like to define a table with a "name", a "start_date" and a
> "stop_date" columns, with a constraint that ensures that 2 records with
> ovelapping dates don't share the same name. Is there a way to define
> such a constraint?

CREATE TABLE T(
NAME TEXT
,START_DATE DATE
,STOP_DATE DATE
);

CREATE OR REPLACE FUNCTION F() RETURNS TRIGGER AS $$
BEGIN
IF EXISTS (
SELECT 1
FROM T
WHERE NAME = NEW.NAME
AND (START_DATE, STOP_DATE)
OVERLAPS
(NEW.START_DATE, NEW.STOP_DATE)
OR STOP_DATE = NEW.START_DATE
)
THEN
RAISE EXCEPTION 'WHATCHA DOIN'' FOO';
RETURN NULL;
END IF;
RETURN NEW;
END;
$$ LANGUAGE PLPGSQL;

CREATE TRIGGER T_T
BEFORE INSERT ON T
FOR EACH ROW
EXECUTE PROCEDURE F();

INSERT INTO T VALUES ('FOO','2007-1-1','2007-1-3'); -- OK

INSERT INTO T VALUES ('FOO','2007-1-4','2007-1-6'); -- OK

INSERT INTO T VALUES ('FOO','2007-1-6','2007-1-8'); -- WILL BARF

Browse pgsql-sql by date

  From Date Subject
Next Message Daniel Drotos 2007-10-09 13:11:44 array handling on 8.0.3
Previous Message A. Kretschmer 2007-10-08 11:59:06 Re: Get different sums from the same table in one query