列值的 Postgres DB 约束

use*_*365 0 sql postgresql

我对 username + user_status 列有一个 UNIQUE 约束,这样我们就不允许两个具有相同名称和状态的用户。但是,我希望这仅适用于状态字段为“ACTIVE”但允许任意数量的具有相同用户名和“INACTIVE”状态的记录的情况。这可能吗?

a_h*_*ame 5

您可以创建过滤的唯一索引:

create unique index on the_table (username)
where user_status = 'ACTIVE';
Run Code Online (Sandbox Code Playgroud)