Loading topic
INSERT ... ON CONFLICT. The statement has to decide what "the same key" means, and a unique constraint or unique index is the only thing that can define i8 min readINSERT that collides with a row already in the table. This chapter reproduces that failure and shows exactly what PostgreSQL reports. It then looks at what the failure does to your statement and transaction, and why the two usual hand-written6 min readON CONFLICT that names which uniqueness rule counts as a conflict. This chapter assumes you can write a basic INSERT, know what primary keys and unique constraints are, and can run statements in psql or another PostgreSQL client. It also assumes you have seen6 min readSELECT, INSERT and UPDATE statements, know what primary keys and unique constraints are, and can run statements in psql or another PostgreSQL client. Earlier chapters covered why upserts need a unique constraint and how a plain INSERT fails on a dup7 min readSELECT, INSERT and UPDATE statements, know what primary keys and unique constraints are, and can run statements in psql or another PostgreSQL client. Earlier chapters covered conflict targets and DO NOTHING. Here you will learn what DO UPDATE does7 min readINSERT ... ON CONFLICT (...) DO UPDATE and know what a unique constraint is. Both are covered in earlier chapters. Here the focus is the EXCLUDED row: what it contains, how to tell it apart from the existing row, and where it causes errors.7 min readINSERT ... ON CONFLICT DO UPDATE and use EXCLUDED, as covered in the previous chapters. You should also know what a row version (tuple) is in PostgreSQL, at least roughly. The examples use the product_stock table from earlier in this tutorial.6 min readON CONFLICT DO NOTHING and ON CONFLICT DO UPDATE with the EXCLUDED row. The examples7 min readINSERT ... ON CONFLICT DO UPDATE and use EXCLUDED. It also assumes you have a unique constraint to use as the conflict target. The examples use the product_stock table from earlier chapters:6 min readINSERT ... ON CONFLICT stays correct when many sessions write the same key at once, and why the common "check, then insert" pattern does not. It assumes you can write INSERT ... ON CONFLICT DO UPDATE, you know what EXCLUDED is, and you know the basics of transactions 7 min readON CONFLICT DO NOTHING, DO UPDATE, and EXCLUDED. You should also be comfortable with unique constraints and with running statements in psql. By the end you should be able to translate an upsert between the two syntaxes, name the beha7 min readINSERT ... ON CONFLICT DO NOTHING and DO UPDATE with EXCLUDED. It also assumes you know what a unique index is and how to read a query result in psql. Upserts work correctly in the cases covered earlier. The three problems below don't raise errors, so they us7 min read