Idempotent Constraint And Index Migration

CREATE INDEX IF NOT EXISTS and DROP CONSTRAINT IF EXISTS keep migrations re-runnable; ADD CONSTRAINT has none, so a DO block queries pg_constraint first.

SqlConfig Management

Code

snippet
-- Migration scripts must be re-runnable: indexes have IF NOT EXISTS, constraints do not
CREATE INDEX IF NOT EXISTS idx_orders_customer_created
    ON orders (customer_id, created_at DESC);

-- ADD CONSTRAINT has no IF NOT EXISTS: probe pg_constraint first, then attach
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'orders_customer_fk'
          AND conrelid = 'orders'::regclass
    ) THEN
        ALTER TABLE orders
            ADD CONSTRAINT orders_customer_fk
            FOREIGN KEY (customer_id) REFERENCES customers (id);
    END IF;
END
$$;

-- The drop direction is idempotent the same way
DROP INDEX IF EXISTS idx_orders_legacy;
ALTER TABLE orders DROP CONSTRAINT IF EXISTS orders_legacy_check;

Inside the snippet

Several statements share this file — SELECT / CREATE / ALTER, with pg_constraint among the objects involved.

Clause by clause, expect: a WHERE clause narrowing which rows one statement affects; a foreign-key REFERENCES guard tying rows to the parent table.

Putting it to use

The pg_constraint table is the working surface here.

Core lines

DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'orders_customer_fk'
AND conrelid = 'orders'::regclass
) THEN
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id) REFERENCES customers (id);
CREATE INDEX IF NOT EXISTS idx_orders_customer_created
ON orders (customer_id, created_at DESC);
ALTER TABLE orders DROP CONSTRAINT IF EXISTS orders_legacy_check;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `pg_constraint`.