首页 > 解决方案 > 仅对非空字符串列应用唯一索引

问题描述

我的 Postgres DB 中有一个字符串列,它有一个唯一索引,但是当该列为空时,我想在某些行中允许重复值。

我希望我的唯一索引允许空值。我怎样才能做到这一点?

我的 postgres 模型的当前代码:

my_field string `gorm:"uniqueIndex"`

标签: postgresqlgrails-orm

解决方案


您可以创建部分索引:

create unique index on the_table (the_column)
where the_column <> '';

根据您的要求,您可能还想排除其中the_column的行null


推荐阅读