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.
Code
-- 唯一约束由一个同名 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `tags`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.