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.

SqlData Integrity

Code

snippet
-- 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

FAQ

Which tables does the SQL touch?
`payment_methods`.