snippetsqlMinor
How to check record if exists before insert with PostgreSQL?
Viewed 0 times
postgresqlinserthowwithrecordexistsbeforecheck
Problem
I have a record:
If the
When create a table, it's possible to use
insert into posts(id, title, body) values(1, 'First post', 'Awesome');If the
First post title and Awesome body already exist in the db, I want to ignore it.When create a table, it's possible to use
IF NOT EXISTS syntax. For inserting, is there an easy way?Solution
if you create a unique key constraint on title & body columns, you can use insert statement as below to ignore if record already exists
insert into posts(id, title, body) values (1, 'First post', 'Awesome') on conflict (title, body) do nothing;Code Snippets
insert into posts(id, title, body) values (1, 'First post', 'Awesome') on conflict (title, body) do nothing;Context
StackExchange Database Administrators Q#316319, answer score: 3
Revisions (0)
No revisions yet.