From: | Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com> |
---|---|
To: | Andreas Kretschmer <akretschmer(at)spamfence(dot)net>, pgsql-sql(at)postgresql(dot)org |
Subject: | Re: unique constraint definition within create table |
Date: | 2015-12-02 14:59:58 |
Message-ID: | 565F076E.20608@aklaver.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
On 12/01/2015 10:36 PM, Andreas Kretschmer 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?
http://www.postgresql.org/docs/9.4/interactive/sql-createtable.html
Shows that expressions are not allowed in UNIQUE constraints.
"UNIQUE ( column_name [, ... ] ) index_parameters
whereas
http://www.postgresql.org/docs/9.4/interactive/sql-createindex.html
"CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ name ] ON table_name [ USING
method ]
( { column_name | ( expression ) } ..."
does.
So no there is not a way to do that in the CREATE TABLE command. You can
bundle the commands though:
BEGIN;
create table foo(u1 int,u2 int);
create unique index idx_foo on foo(least(u1,u2),greatest(u1,u2));
COMMIT;
to make sure they either both succeed or fail.
>
> Thx.
>
> Andreas
>
--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com
From | Date | Subject | |
---|---|---|---|
Next Message | David G. Johnston | 2015-12-02 18:42:42 | Re: unique constraint definition within create table |
Previous Message | Tom Lane | 2015-12-02 14:46:09 | Re: unique constraint definition within create table |