pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Richard Huxton <dev@archonet.com>
To: Kevin Houle <kevin@houle.org>
To: pgsql-sql@postgresql.org
Subject: Re: Dublicates pairs in a table.
Date: Fri, 27 Sep 2002 13:54:54 +0100
Message-ID: <200209271354.54187.dev@archonet.com> (raw)
In-Reply-To: <3D910CEB.30704@houle.org>
References: <000201c25d90$87230c10$6500000a@IT000>
	<3D910CEB.30704@houle.org>

On Wednesday 25 Sep 2002 2:10 am, Kevin Houle wrote:
> I have the same issue with a table that currently holds well
> over 600,000 rows. The case you left out is this:
>
>   INSERT INTO test (c1,c2) VALUES('a','c');
>   INSERT INTO test (c1,c2) VALUES('c','a');
>
> I want that to fail, but I haven't been able to get it to fail
> using unique indexes. I presume ordering is significant. Instead,
> I am doing a SELECT prior to insert to insure the pair doesn't
> already exist. If you've been able to get order-independent
> pairs restricted to being unique using indexes, I'd like to know
> about it. :-)

Functional indexes sir - define a function that puts the columns into a sorted 
order.

richardh=> CREATE TABLE foo (a text, b text);
CREATE
richardh=> CREATE UNIQUE INDEX foo_both_uniq ON foo ( ord_fn(a,b) );
ERROR:  DefineIndex: index function must be marked iscachable
richardh=> \i ordfn.txt
DROP
CREATE
richardh=> CREATE UNIQUE INDEX foo_both_uniq ON foo ( ord_fn(a,b) );
CREATE
richardh=> insert into foo values ('aa','bb');
INSERT 332596 1
richardh=> insert into foo values ('aa','cc');
INSERT 332597 1
richardh=> insert into foo values ('bb','aa');
ERROR:  Cannot insert a duplicate key into unique index foo_both_uniq
richardh=> insert into foo values ('aa','bb');
ERROR:  Cannot insert a duplicate key into unique index foo_both_uniq

Function defined as:
CREATE FUNCTION ord_fn (text,text) RETURNS text AS '
SELECT (CASE
    WHEN $1 < $2
    THEN $1 || $2
    ELSE $2 || $1
    END) as t;
' LANGUAGE SQL WITH (iscachable);

-- 
  Richard Huxton



view thread (10+ messages)  latest in thread

Message-ID: <200209271354.54187.dev@archonet.com>
Permalink:  ../200209271354.54187.dev@archonet.com/
Also on:    postgresql.org/message-id/200209271354.54187.dev@archonet.com

 · 

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: dev@archonet.com, kevin@houle.org
  Subject: Re: Dublicates pairs in a table.
  In-Reply-To: <200209271354.54187.dev@archonet.com>

* 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