从 PostgreSQL 中删除未命名的约束

Remove unnamed constraint from PostgreSQL

在 PostgreSQL 中,我有以下 table 定义

create table file(
    file_id int generated by default as identity primary key,
    file_name text UNIQUE not null
);

我的问题是:如何删除 file_name 上的唯一约束?

对于这种约束,Postgres 使用的默认命名策略是 tablename_columnname_key,因此在您的情况下它将是 file_file_name_key

所以你可以使用

alter table file drop constraint file_file_name_key;

如果您不想依赖默认的命名策略,可以使用以下查询来检索名称:

select constraint_name
from information_schema.key_column_usage
where table_name = 'file'
  and table_schema = 'public'
  and column_name = 'file_name';

您必须查询元数据 (pg_constraintpg_indexpg_attribute) 以找出由您的列上的唯一索引实现的约束的名称.

PostgreSQL 使用内部逻辑自动生成名称(请参阅其他答案),但依赖它很脆弱:如果已经存在具有该名称的约束,PostgreSQL 将通过附加数字来消除歧义。

任何约束总是有名称的 - 只是如果您不指定 Postgres 或 ORM(例如 Hinernate)会自动生成一个名称。

如果您使用 pgAdmin,您只需单击 table,它将在描述中显示约束列表及其名称:

对于上面的示例,我只需要 运行:

ALTER Table word_pairs drop constraint word_pairs_foreign_word_key;

如果你不使用 GUI 你可以这样找到约束名称:

SELECT tc.constraint_name FROM information_schema.table_constraints 
AS tc WHERE tc.constraint_type='UNIQUE' 
AND tc.table_name='word_pairs';

(这是对 this answer 的简化改编)