Why DROP INDEX Fails On Constraint Indexes

A unique constraint owns a same-named index: DROP INDEX fails with a dependency error, while DROP CONSTRAINT removes both in one step.

SqlData Integrity

Code

snippet
-- 唯一约束由一个同名 b-tree 索引支撑
CREATE TABLE tags (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    label text NOT NULL,
    CONSTRAINT tags_label_key UNIQUE (label)
);

INSERT INTO tags (label) VALUES ('postgres');

-- 违反时报错的是约束名:
-- ERROR:  duplicate key value violates unique constraint "tags_label_key"
-- INSERT INTO tags (label) VALUES ('postgres');

-- 直接删支撑索引会失败:依赖它的是约束
-- ERROR:  cannot drop index tags_label_key because other objects depend on it
-- DROP INDEX tags_label_key;

-- 正确途径:删约束,索引随之一起消失
ALTER TABLE tags DROP CONSTRAINT tags_label_key;

-- 约束删除后,重复值不再被拦截
INSERT INTO tags (label) VALUES ('postgres');

SELECT label, count(*) FROM tags GROUP BY label ORDER BY label;

How the snippet works

SELECT / INSERT / CREATE / ALTER statements share the script, touching tags.

Breaking the statements into their working parts: COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the tags table.

Statements that matter

SELECT label, count(*) FROM tags GROUP BY label ORDER BY label;
CREATE TABLE tags (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    label text NOT NULL,
    CONSTRAINT tags_label_key UNIQUE (label)
);
INSERT INTO tags (label) VALUES ('postgres');

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`tags`.