Idempotent Seed Insert With NOT EXISTS
Seed reference data idempotently with INSERT SELECT plus a WHERE NOT EXISTS guard, so replaying the script neither duplicates rows nor needs a conflict target.
Code
-- When reference data has no unique key to use as a conflict target, guard an idempotent seed with a WHERE NOT EXISTS anti-join
-- Replaying the whole script neither errors nor duplicates rows
CREATE TABLE payment_methods (
code text PRIMARY KEY,
label text NOT NULL,
sort_order int NOT NULL DEFAULT 0
);
-- Single-row seed: when the row exists, INSERT ... SELECT inserts zero rows
INSERT INTO payment_methods (code, label, sort_order)
SELECT 'card', 'Bank card', 1
WHERE NOT EXISTS (SELECT 1 FROM payment_methods WHERE code = 'card');
-- Bulk seed: anti-join over the whole set so existing codes are not inserted twice
INSERT INTO payment_methods (code, label, sort_order)
SELECT v.code, v.label, v.sort
FROM (VALUES
('bank_transfer', 'Bank transfer', 2),
('wallet', 'Wallet', 3)
) AS v(code, label, sort)
WHERE NOT EXISTS (
SELECT 1 FROM payment_methods pm WHERE pm.code = v.code
);
SELECT code, label FROM payment_methods ORDER BY sort_order;What the code does
What runs here is SELECT / INSERT / CREATE — payment_methods are the objects involved.
What the statements actually assemble: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.
Applying it
Run the statement against the payment_methods table.
Statements that matter
INSERT INTO payment_methods (code, label, sort_order)
SELECT v.code, v.label, v.sort
FROM (VALUES
('bank_transfer', 'Bank transfer', 2),
('wallet', 'Wallet', 3)
) AS v(code, label, sort)
WHERE NOT EXISTS (
SELECT 1 FROM payment_methods pm WHERE pm.code = v.code
);
INSERT INTO payment_methods (code, label, sort_order)
SELECT 'card', 'Bank card', 1
WHERE NOT EXISTS (SELECT 1 FROM payment_methods WHERE code = 'card');
CREATE TABLE payment_methods (
code text PRIMARY KEY,
label text NOT NULL,
sort_order int NOT NULL DEFAULT 0
);
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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does the SQL touch?
- `payment_methods`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.