Reading history

SQL UPSERT: INSERT ON CONFLICT DO UPDATE

5 min read 0 views

Learn SQL UPSERT to insert or update in one statement: ON CONFLICT DO UPDATE, the excluded row, DO NOTHING, INSERT OR REPLACE, and MySQL and MERGE equivalents.

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 INSERT fails on a duplicate key
  • ON CONFLICT … DO UPDATE and the excluded row
  • ON CONFLICT … DO NOTHING
  • Why INSERT OR REPLACE can 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 INSERT of 'P-1' fails because sku is 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, the DO UPDATE part runs instead of the insert.
  • excluded is the row you tried to insert, so excluded.qty is 10; stock.qty is 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 NOTHING keeps 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’s REPLACE INTO works the same way) deletes the old row and inserts a new one. The updated column 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 SELECT needs a WHERE clause (even WHERE true) before ON CONFLICT, so the parser does not mistake ON for part of a join.

UPSERT in Other Databases

DatabaseSyntax
PostgreSQL, SQLiteINSERT … ON CONFLICT (key) DO UPDATE SET col = excluded.col
MySQL, MariaDBINSERT … 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

  1. Using SELECT-then-INSERT in application code, which can create duplicates when two requests arrive together.
  2. Upserting on a column without a unique constraint; the database has no conflict to detect.
  3. Using REPLACE when you mean update, and losing columns or child rows.
  4. Writing SET qty = qty + qty, which doubles the old value instead of adding the new one. Use excluded.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.
  • excluded refers to the values you tried to insert.
  • DO NOTHING skips duplicates; REPLACE deletes and re-inserts.
  • MySQL uses ON DUPLICATE KEY UPDATE; SQL Server uses MERGE.

Next: How to Find and Delete Duplicate Rows in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *