简体   繁体   中英

Adding a unique constraint on a nullable column in PSQL

I am having a table with two columns. Want to add unique constraint on both columns. One of the column is nullable.

I m trying with this syntax:

ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, (coalesce(a_name, '')));

Its prompting error at or near "("

You don't need to use coalesce in that case. Just create constraint in the usual way:

ALTER TABLE a ADD CONSTRAINT a_unq UNIQUE (a_id, a_name);

If you uactually need the solution was in PostgreSQL multiple nullable columns in unique constraint : just create UNIQUE index on table, it will stop inserts even if it isn't a constraint declared in table definition:

CREATE UNIQUE INDEX ex_12345 ON example
        (coalesce(FIELD1, -1)
        , coalesce(FIELD2, -1)
        , coalesce(FIELD3, -1)
        , coalesce(FIELD4, -1)
        , coalesce(FIELD5, -1)
        )
        ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM