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.
Code
-- 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
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.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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.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.
FAQ
- What objects does the SQL involve?
- The references are `pg_constraint`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.