Often you do not know whether a row already exists. A shop receives a delivery: if the item is in stock, increase the quantity; if not, add it. Checking first with a SELECT and then choosing INSERT or UPDATE takes two steps, and two users can collide between them. An UPSERT (update or insert) does the whole job in one statement. This lesson uses INSERT … ON CONFLICT, the syntax shared by PostgreSQL and SQLite, and shows the MySQL and SQL Server versions.
In this lesson you will learn
- Why a plain
INSERTfails on a duplicate key ON CONFLICT … DO UPDATEand theexcludedrowON CONFLICT … DO NOTHING- Why
INSERT OR REPLACEcan lose data - Upserting many rows at once, and other databases’ syntax
You should know INSERT, UPDATE and DELETE and primary keys.
Insert or Update
CREATE TABLE stock (
sku TEXT PRIMARY KEY,
item TEXT,
qty INTEGER
);
INSERT INTO stock VALUES ('P-1', 'Pen', 40), ('N-1', 'Notebook', 15);
-- fails: a plain INSERT cannot add a second row with the same key
INSERT INTO stock VALUES ('P-1', 'Pen', 10);
-- UPSERT: insert, or update the existing row if the key already exists
INSERT INTO stock (sku, item, qty) VALUES ('P-1', 'Pen', 10)
ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
INSERT INTO stock (sku, item, qty) VALUES ('E-1', 'Eraser', 25)
ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT * FROM stock ORDER BY sku;
Output
Error: UNIQUE constraint failed: stock.sku
+-----+----------+-----+
| sku | item | qty |
+-----+----------+-----+
| E-1 | Eraser | 25 |
| N-1 | Notebook | 15 |
| P-1 | Pen | 50 |
+-----+----------+-----+
(3 rows)
- The plain
INSERTof'P-1'fails becauseskuis the primary key and that value already exists. ON CONFLICT (sku)names the unique column to watch. If the new row would clash on it, theDO UPDATEpart runs instead of the insert.excludedis the row you tried to insert, soexcluded.qtyis 10;stock.qtyis the value already stored. The pen quantity becomes 40 + 10 = 50.- The eraser did not exist, so there was no conflict and it was simply inserted.
- The conflict target must be a primary key or a column (or set of columns) with a unique constraint or unique index.
DO NOTHING, REPLACE and Bulk Upserts
CREATE TABLE stock (sku TEXT PRIMARY KEY, item TEXT, qty INTEGER, updated TEXT DEFAULT 'original');
INSERT INTO stock (sku, item, qty) VALUES ('P-1', 'Pen', 40), ('N-1', 'Notebook', 15);
-- DO NOTHING: keep the existing row, skip the new one silently
INSERT INTO stock (sku, item, qty) VALUES ('N-1', 'Notebook', 99)
ON CONFLICT (sku) DO NOTHING;
-- INSERT OR REPLACE deletes the old row and inserts a new one,
-- so columns you did not supply go back to their defaults
UPDATE stock SET updated = 'edited' WHERE sku = 'P-1';
INSERT OR REPLACE INTO stock (sku, item, qty) VALUES ('P-1', 'Pen', 5);
SELECT * FROM stock ORDER BY sku;
-- Upsert many rows at once from another query
INSERT INTO stock (sku, item, qty)
SELECT 'N-1', 'Notebook', 10
UNION ALL SELECT 'R-1', 'Ruler', 30
WHERE true
ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT sku, item, qty FROM stock ORDER BY sku;
Output
+-----+----------+-----+----------+
| sku | item | qty | updated |
+-----+----------+-----+----------+
| N-1 | Notebook | 15 | original |
| P-1 | Pen | 5 | original |
+-----+----------+-----+----------+
(2 rows)
+-----+----------+-----+
| sku | item | qty |
+-----+----------+-----+
| N-1 | Notebook | 25 |
| P-1 | Pen | 5 |
| R-1 | Ruler | 30 |
+-----+----------+-----+
(3 rows)
DO NOTHINGkeeps the existing notebook row (qty 15) and quietly skips the new one. It is handy for “insert if missing” jobs such as importing data that may already be loaded.INSERT OR REPLACE(SQLite; MySQL’sREPLACE INTOworks the same way) deletes the old row and inserts a new one. Theupdatedcolumn had been set to'edited', but it went back to its default,'original', because the statement did not supply it. A delete can also fire cascades on child tables.- An upsert can take its rows from a
SELECT: the notebook was updated (15 + 10 = 25) and the ruler inserted, in one statement. - In SQLite the
SELECTneeds aWHEREclause (evenWHERE true) beforeON CONFLICT, so the parser does not mistakeONfor part of a join.
UPSERT in Other Databases
| Database | Syntax |
|---|---|
| PostgreSQL, SQLite | INSERT … ON CONFLICT (key) DO UPDATE SET col = excluded.col |
| MySQL, MariaDB | INSERT … ON DUPLICATE KEY UPDATE qty = qty + VALUES(qty) (newer MySQL uses a row alias instead of VALUES()) |
| SQL Server, Oracle, PostgreSQL 15+ | MERGE INTO stock USING … ON … WHEN MATCHED THEN UPDATE … WHEN NOT MATCHED THEN INSERT … |
Common Mistakes
- Using SELECT-then-INSERT in application code, which can create duplicates when two requests arrive together.
- Upserting on a column without a unique constraint; the database has no conflict to detect.
- Using
REPLACEwhen you mean update, and losing columns or child rows. - Writing
SET qty = qty + qty, which doubles the old value instead of adding the new one. Useexcluded.qty.
Practice Exercises
Exercise 1. A page_views(page TEXT PRIMARY KEY, views INTEGER) table counts visits. Write one statement that adds a view for '/home', creating the row the first time.
Show answer
INSERT INTO page_views (page, views) VALUES ('/home', 1)
ON CONFLICT (page) DO UPDATE SET views = page_views.views + 1;
Exercise 2. Update a stock row’s quantity only if the new value is larger than the stored one.
Show answer
INSERT INTO stock (sku, item, qty) VALUES ('P-1', 'Pen', 60)
ON CONFLICT (sku) DO UPDATE SET qty = excluded.qty
WHERE excluded.qty > stock.qty;
The WHERE clause on DO UPDATE lets the update happen only when the condition holds.
Frequently Asked Questions
Is an UPSERT atomic?
Yes. The check and the insert or update happen in a single statement, so two sessions cannot both insert the same key.
How do I know whether a row was inserted or updated?
PostgreSQL and SQLite support RETURNING to get the final row back. In PostgreSQL, RETURNING (xmax = 0) AS inserted is a common trick; otherwise, compare a column such as a created timestamp.
Summary
- An UPSERT inserts a new row or updates the existing one in a single statement.
excludedrefers to the values you tried to insert.DO NOTHINGskips duplicates;REPLACEdeletes and re-inserts.- MySQL uses
ON DUPLICATE KEY UPDATE; SQL Server usesMERGE.
