今天一个一起搬砖的兄弟同事过来问,为什么他的索引删不掉?我过去看了下:
执行脚本:

drop index constraint_unique

报错如下:
在这里插入图片描述

执行时出错 确认要继续执行吗?
单击“详细信息”了解详情。

SQL错误码: = 2BP01
ERROR: cannot drop index constraint_unique because constraint constraint_unique on table t1 requires it
Hint: You can drop constraint constraint_unique on table t1 instead.
行号: 19

报错大意是:不能删除索引constraint_unique因为约束constraint_unique在表t1上引用了它。
暗示:你可以删除约束constraint_unique在表t1上来代替它。
于是我执行drop constraint的语句,删除成功。
alter table t1 drop CONSTRAINT constraint_unique;
究其原因,该索引并不是通过create index直接创建的,而是在创建唯一约束的时候顺带创建的。实验发现,openGauss在创建唯一约束的时候,同时会创建一个唯一索引,当然在删除唯一约束的同时,也会删除掉创建唯一约束时附带创建的唯一索引;
在这里插入图片描述

但是在创建唯一索引的时候,并不会同时显式创建一个唯一约束。通过创建索引直接创建的索引,好像有点绕咔咔咔,则可以直接通过drop index的方式删除。
在这里插入图片描述

再对比下创建唯一索引和唯一约束后,在插入重复数据时的区别:

  1. 唯一索引:插入重复数据时报错,插入时也报唯一约束冲突
    在这里插入图片描述

ERROR: duplicate key value violates unique constraint “idx_unique”
Detail: Key (c1)=(1) already exists.

  1. 唯一约束:
    在这里插入图片描述

ERROR: duplicate key value violates unique constraint “constraint_unique”
Detail: Key (c1)=(1) already exists.
那么约束是否存在呢?我对于增加唯一约束的场景,尝试执行 drop constraint的操作,系统会报错constraint不存在,这说明确实没有创建约束。
在这里插入图片描述

执行时出错 确认要继续执行吗?
单击“详细信息”了解详情。
SQL错误码: = 42704
ERROR: constraint “idx_unique” of relation “test” does not exist
行号: 2

来自:如鱼得水

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐