📜  upsert postgres - SQL (1)

📅  最后修改于: 2023-12-03 15:05:46.250000             🧑  作者: Mango

Upsert Postgres - SQL

Upsert(PostgreSQL) is a combination of two operation, insert and update, where if the data exists, it updates it and if it doesn't exist, it inserts it. This can be done in a single query which makes it efficient and helps to prevent race conditions between multiple queries.

In PostgreSQL, upsert can be done using the INSERT statement with the ON CONFLICT clause. Here's an example:

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3)
ON CONFLICT (unique_column) DO UPDATE SET column1 = EXCLUDED.column1, column2 = EXCLUDED.column2;

This query first tries to insert a new row into the table table_name, but if there is a conflict with the value in the unique_column, it updates the values in column1 and column2 with the EXCLUDED keywords.

The EXCLUDED keyword allows us to access the values of the row that would have been inserted if there were no conflict.

PostgreSQL also provides an alternative syntax using the WHERE clause instead of ON CONFLICT. Here's an example:

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3)
ON CONFLICT (unique_column)
WHERE column1 != EXCLUDED.column1 OR column2 != EXCLUDED.column2
DO UPDATE SET column1 = EXCLUDED.column1, column2 = EXCLUDED.column2;

This query is similar to the previous one, but instead of specifying the values to update, we use a WHERE clause to check if there are any differences between the existing row and the new row to be inserted.

Overall, upsert in PostgreSQL is a very useful feature that can save time and reduce the complexity of your queries.

Conclusion

In this article, we've seen how to use upsert in PostgreSQL, which is a combination of insert and update operations. We've also seen how to use the ON CONFLICT and WHERE clauses to handle conflicts and update rows as needed. Upsert is a powerful tool that can simplify your queries and improve their performance, so go ahead and try it out in your next project!