How to do UPSERT query in PostgreSQL

WITH upsert AS (<update-query-here> RETURNING *) <insert-query-here>  WHERE NOT EXISTS (SELECT * FROM upsert);

<insert-query-here> Should be of form
“INSERT INTO table_name (column1, column2, …) SELECT ‘column_1_value’, ‘column_2_value’, …”
Hence if update query succeeds, insert query wont execute due to WHERE clause.

Thanks to reference http://www.the-art-of-web.com/sql/upsert/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s