IF NOT EXISTS Skips Definition Mismatch

CREATE INDEX IF NOT EXISTS compares names only: an existing index with different columns silently wins, so migrations can run on the wrong shape forever.

SqlConfig Management

Code

snippet
-- IF NOT EXISTS 只比对名字:同名索引即使定义完全不同也会被原样保留
-- 文档原话:there is no guarantee that the existing index is anything
-- like the one that would have been created
CREATE TEMP TABLE events (
    event_id    bigint PRIMARY KEY,
    tenant_id   bigint NOT NULL,
    happened_at timestamptz NOT NULL
);
INSERT INTO events SELECT g, g % 4, now() - (g || ' minutes')::interval
FROM generate_series(1, 10000) g;

-- 旧迁移留下的“错误形态”:单列索引,名字却像复合索引
CREATE INDEX idx_events_tenant_time ON events (tenant_id);

-- 新迁移用 IF NOT EXISTS 幂等补建复合索引:名字撞上 → NOTICE + skip
CREATE INDEX IF NOT EXISTS idx_events_tenant_time
    ON events (tenant_id, happened_at);

SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'events'
ORDER BY indexname;
-- 定义仍是单列 (tenant_id):definition mismatch 不报错也不自动修正
DROP TABLE events;

How it works

SELECT / INSERT / CREATE statements share the script, touching events, generate_series and pg_indexes.

events starts life inside this file as a session-local temp table — nothing needs to pre-exist, and the session’s end removes it.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Using it

Setup is internal: the session-local tables it queries (events) are made by the file, so a single complete run against a scratch database suffices.

Key statements

INSERT INTO events SELECT g, g % 4, now() - (g || ' minutes')::interval
FROM generate_series(1, 10000) g;
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'events'
ORDER BY indexname;
CREATE TEMP TABLE events (
    event_id    bigint PRIMARY KEY,
    tenant_id   bigint NOT NULL,
    happened_at timestamptz NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`events`, `generate_series`, `pg_indexes`.