简体   繁体   中英

Postgres Unique constraint based column value

CREATE TABLE employee (
    id varchar(40) NOT NULL,
    legacy_id varchar(40) NOT NULL,
    short_name varchar(255) NULL,   
    is_deleted bool NOT NULL DEFAULT false,
    CONSTRAINT employee_pkey PRIMARY KEY (id)
)

I want to plan for unique constraint like this

The table must have these constraint

1. Unique constraint is required on column 'legacy_id' and 'is_deleted = false'. Its okay to have multiple values with legacy_id and is_deleted = true. 

Is there any way to achieve this

You cannot have a constraint for that, but a partial unique index will do just as well:

CREATE UNIQUE INDEX ON employee (legacy_id)
   WHERE is_deleted;

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