Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: INSERT if does not exist already

I'm using Python to write to a postgres database:

sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES (" sql_string += hundred + ", '" + hundred_slug + "', " + status + ");" cursor.execute(sql_string) 

But because some of my rows are identical, I get the following error:

psycopg2.IntegrityError: duplicate key value     violates unique constraint "hundred_pkey" 

How can I write an 'INSERT unless this row already exists' SQL statement?

I've seen complex statements like this recommended:

IF EXISTS (SELECT * FROM invoices WHERE invoiceid = '12345') UPDATE invoices SET billed = 'TRUE' WHERE invoiceid = '12345' ELSE INSERT INTO invoices (invoiceid, billed) VALUES ('12345', 'TRUE') END IF 

But firstly, is this overkill for what I need, and secondly, how can I execute one of those as a simple string?

like image 416
AP257 Avatar asked Nov 01 '10 14:11

AP257


People also ask

How do you insert if row does not exist in Postgres?

Firstly we have to mention the table name followed by column names (attributes) where we want to insert rows. Secondly, we must enter the values, separated by a comma after the VALUE clause. Finally, every value must be in the same order as the sequence of attribute lists is provided while creating a particular table.

How to insert in PostgreSQL?

In PostgreSQL, the INSERT statement is used to add new rows to a database table. As one creates a new database, it has no data initially. PostgreSQL provides the INSERT statement to insert data into the database. Syntax: INSERT INTO table(column1, column2, …) VALUES (value1, value2, …);

How do I add unique values in PostgreSQL?

You need to join against the table, or use WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE ...) to make the INSERT INTO ... SELECT ... 's SELECT part return zero rows if the row already exists in the target table. Note, though, that that's still subject to race conditions.

Does Postgres support Upsert?

PostgreSQL added the ON CONFLICT target action clause to the INSERT statement to support the upsert feature. In this statement, the target can be one of the following: (column_name) – a column name. ON CONSTRAINT constraint_name – where the constraint name could be the name of the UNIQUE constraint.


1 Answers

Postgres 9.5 (released since 2016-01-07) offers an "upsert" command, also known as an ON CONFLICT clause to INSERT:

INSERT ... ON CONFLICT DO NOTHING/UPDATE 

It solves many of the subtle problems you can run into when using concurrent operation, which some other answers propose.

like image 121
Arie Avatar answered Oct 08 '22 14:10

Arie