Full answer
Sample schema and data:
sql
CREATE TABLE customers (id int, email text);
INSERT INTO customers VALUES (1, 'a@x.in'), (2, 'b@x.in'), (3, 'a@x.in');sql
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);Result on PostgreSQL 17:
text
ERROR: could not create unique index "customers_email_key"sql
SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;Result:
text
index_name | indisvalid
---------------------+------------
customers_email_key | f
(1 row)sql
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);Output:
text
ERROR: relation "customers_email_key" already existssql
DROP INDEX CONCURRENTLY customers_email_key;PostgreSQL returns:
text
DROP INDEXsql
DELETE FROM customers WHERE id = 3;Result on PostgreSQL 17:
text
DELETE 1sql
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);Result:
text
CREATE INDEXsql
SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;Output:
text
index_name | indisvalid
---------------------+------------
customers_email_key | t
(1 row)The concurrent build fails on the duplicate email, but the catalog still holds customers_email_key with indisvalid = false. A retry fails at once because the name is taken. Dropping the leftover index concurrently, removing the duplicate and rebuilding produces a valid index. Each concurrent command runs alone because none of them can run inside a transaction block. Migration tools should detect invalid indexes before retrying, and a periodic check for indisvalid = false catches leftovers from cancelled deployments.
sql
CREATE TABLE customers (id int, email text);
INSERT INTO customers VALUES (1, 'a@x.in'), (2, 'b@x.in'), (3, 'a@x.in');
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);
SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);
DROP INDEX CONCURRENTLY customers_email_key;
DELETE FROM customers WHERE id = 3;
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);
SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Failed concurrent builds leave INVALID indexes
- Invalid indexes are maintained but unused
- They block retries with the same name
- Drop concurrently, fix, rebuild
- Monitor indisvalid
Common mistakes
- Ignoring leftover invalid indexes
- Retrying without removing the failed index
Follow-ups
- Why does a concurrent build need two table scans?
- What does REINDEX CONCURRENTLY do?
Tips
- Show indisvalid