Re: unique constraint definition within create table

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Andreas Kretschmer <akretschmer(at)spamfence(dot)net>
Cc: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: unique constraint definition within create table
Date: 2015-12-02 18:42:42
Message-ID: CAKFQuwZeW5W9JuigEOo9ouxPvm_4bZbufbDpmLg=L+gLSw-0bA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Tue, Dec 1, 2015 at 11:36 PM, Andreas Kretschmer <
akretschmer(at)spamfence(dot)net> wrote:

> Hi @ll,
>
> i'm trying to create a table with 2 int-columns and a constraint that a
> pair of (x,y) cannot be as (y,x) inserted:
>
> test=# create table foo(u1 int,u2 int, unique
> (least(u1,u2),greatest(u1,u2)));
> ERROR: syntax error at or near "("
> LINE 1: create table foo(u1 int,u2 int, unique (least(u1,u2),greates...
>
>
> I know, i can solve that in this way:
>
> test=*# create table foo(u1 int,u2 int);
> CREATE TABLE
> test=*# create unique index idx_foo on foo(least(u1,u2),greatest(u1,u2));
> CREATE INDEX
>
>
> But is there a way to define the unique constraint within the create table
> - command?
>

​You might consider adding a table constraint "u1 <= u2"​. You could also
consider adding a trigger that munges data on INSERT/UPDATE so that this
constraint is met regardless of the order supplied by the user.

David J.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Sribeiro 2015-12-02 19:41:36 Re: ERROR while creating new user - could not open relation mapping file global/pg_filenode.map
Previous Message Adrian Klaver 2015-12-02 14:59:58 Re: unique constraint definition within create table