Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Use On Conflict Do Nothing In Postgres Like Insert Or Ignore In Other Databases

Postgres doesn't have "INSERT OR IGNORE"

Instead, use:

Code

ON CONFLICT (column_name) DO NOTHING;

For example, given this table setup:

Code

CREATE TABLE IF NOT EXISTS public.states (
    db_id SERIAL PRIMARY KEY,
    abbreviation VARCHAR(2) NOT NULL UNIQUE,
    full_name VARCHAR(30)
);

ALTER TABLE public.states ENABLE ROW LEVEL SECURITY;

This INSERT statement can be run multiple times:

Code

INSERT INTO public.states (abbreviation, full_name)
VALUES ('AL', 'Alabama')
ON CONFLICT (abbreviation) DO NOTHING;
;

The first time will insert the data. Subsequent runs will be skipped without throwing errors.