MOCKSTACKS
EN
Questions And Answers

More Tutorials









postgreSQL UPSERT INSERT ON CONFLICT DO UPDATE


Say you have a table called my_table, created in several previous examples. We insert a row, returning PK value of inserted row:

b=# INSERT INTO my_table (name,contact_number) values ('one',333) RETURNING id;
 id
----
 2
(1 row)
INSERT 0 1

Now if we try to insert row with existing unique key it will raise an exception:

b=# INSERT INTO my_table values (2,'one',333);
ERROR: duplicate key value violates unique constraint "my_table_pkey"
DETAIL: Key (id)=(2) already exists.

Upsert functionality offers ability to insert it anyway, solving the conflict:

b=# INSERT INTO my_table values (2,'one',333) ON CONFLICT (id) DO UPDATE SET name =
my_table.name||' changed to: "two" at '||now() returning *;
 id | name | contact_number
----+-----------------------------------------------------------------------------------------
------------------+----------------
 2 | one changed to: "two" at 2016-11-23 08:32:17.105179+00 | 333
(1 row)
INSERT 0 1



Conclusion

In this page (written and validated by ) you learned about postgreSQL UPSERT INSERT ON CONFLICT DO UPDATE . What's Next? If you are interested in completing postgreSQL tutorial, your next topic will be learning about: postgreSQL JSON Support.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.