Duplicate key name in CREATE/ALTER TABLE
Production Risk
Low — DDL fails; existing indexes are unchanged.
ER_DUP_KEYNAME (1061, SQLSTATE 42000) is raised when CREATE TABLE or ALTER TABLE attempts to create two indexes with the same name on the same table.
- 1Migration script adds an index without checking if it already exists
- 2Two ALTER TABLE statements both create an index with the same name
- 3ORM generates duplicate index names on schema sync
CREATE TABLE t (id INT, INDEX idx_id (id), INDEX idx_id (id));
expected output
ERROR 1061 (42000): Duplicate key name 'idx_id'
Fix
Check for existing index before adding
WHEN In migration scripts that may run multiple times.
-- Check first: SHOW INDEX FROM t WHERE Key_name = 'idx_id'; -- In MySQL 8.0 you can use IF NOT EXISTS with ALTER TABLE: ALTER TABLE t ADD INDEX IF NOT EXISTS idx_id (id);
Why this works
IF NOT EXISTS on ADD INDEX (MySQL 8.0+) makes the operation idempotent.
✕ Drop all indexes and recreate them to avoid 1061
Dropping and recreating indexes on large tables is expensive and causes index rebuild downtime.
ALTER TABLE ... ADD INDEX IF NOT EXISTS was introduced, making idempotent index creation possible.
MySQL 8.0 — 1061 ER_DUP_KEYNAME
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev