SQL UPSERT: insert it if it's new, update it if it's there

A delivery arrives, and every product raises the same question: do we already stock it? Then add to the stock level. Is it new? Then create it. Instead of checking first and writing two different statements, an upsert handles both cases in one.

In short: INSERT INTO products (…) VALUES (…) ON CONFLICT (product_id) DO UPDATE SET price = excluded.price; inserts the row. If that product_id already exists, the existing row is updated instead. excluded is the row you tried to insert. With DO NOTHING the row is simply skipped.

Before you start: INSERT, UPDATE and primary keys. An upsert always needs a column that only allows unique values.

Try it now

Every run starts with fresh data. After Run you see the rows of products that your statement changed or added.

Task The supplier's new price list covers two products: product_id 9, '27-inch monitor', 'Electronics', price 269.00 and product_id 13, 'Whiteboard 36 x 24 in', 'Furniture', price 59.90. Load both into products with a single INSERT: new products get stock 0, and for existing ones only the price changes while the stock stays as it is.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

How ON CONFLICT works

An upsert is an ordinary INSERT plus instructions for the case where it would fail. The lever arch file now costs 2.89:

INSERT INTO products (product_id, name, category, price, stock)
VALUES (3, 'Lever arch file, gray', 'Filing', 2.89, 0)
ON CONFLICT (product_id) DO UPDATE SET price = excluded.price;

SELECT * FROM products WHERE product_id = 3;
product_idnamecategorypricestock
3Lever arch file, grayFiling2.89185

The database tries the INSERT first. product_id 3 already exists, and the primary key won't allow a second row. Instead of stopping with an error, it jumps to ON CONFLICT and updates the existing row. After SET you have two views of the data:

  • price or stock on its own is the value already in the table.
  • excluded.price is the value from your INSERT, the one that was turned away.

That is why stock stays at 185 even though the INSERT says 0: SET only touches the price. It is also why you can do arithmetic, such as stock = stock + excluded.stock. The parentheses after ON CONFLICT name the column whose duplicates you are catching, usually the primary key.

One more exercise: booking in a delivery

The rows can come from a SELECT instead of VALUES. SQLite then has one quirk: the SELECT needs a WHERE, even if it's just WHERE true. Otherwise the parser reads the ON of ON CONFLICT as the ON of a join.

Task A delivery came in today and is listed in the goods_in table. Book it into products with a single INSERT … SELECT: for products that already exist, add quantity to stock; create new products with name, category, price and stock = quantity.

goods_in 3 rows, 5 columns
product_idnamecategorypricequantity
4Comfort office chairFurniture18910
7Yellow sticky notes, 12 padsWriting6.99120
13Whiteboard 36 x 24 inFurniture64.96
products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

INSERT OR IGNORE and INSERT OR REPLACE

SQLite has two older shortcuts. INSERT OR IGNORE skips every row that would break a primary key or UNIQUE constraint and inserts the rest, with no error. It does the same as ON CONFLICT DO NOTHING.

INSERT OR REPLACE sounds like "otherwise update", but it does something else: it deletes the existing row and inserts the new one. Anything you leave out is gone afterwards:

INSERT OR REPLACE INTO products (product_id, name, price, stock)
VALUES (3, 'Lever arch file, gray', 2.89, 185);

SELECT * FROM products WHERE product_id = 3;
product_idnamecategorypricestock
3Lever arch file, grayNULL2.89185

The Filing category has vanished because the INSERT didn't mention it. The SQLite docs say exactly this: REPLACE deletes the rows causing the conflict before inserting the new one. MySQL's REPLACE behaves the same way. For "insert or update", use ON CONFLICT DO UPDATE.

One more exercise: filling in missing rows

Task The categories table records who in Purchasing looks after each category. A few categories from products are still missing there. Add every missing category with a single INSERT (leave manager empty for them). The existing rows must not change.

categories 4 rows, 2 columns
categorymanager
PaperSarah Long
WritingSarah Long
FurnitureTom Bradley
ElectronicsTom Bradley
products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

A plain INSERT

Without ON CONFLICT the INSERT stops at the first row that already exists, and nothing is inserted at all. The exercise says: "This value already exists in products.product_id. The column allows each value only once (primary key or UNIQUE)."

Missing WHERE true

INSERT … SELECT … FROM goods_in ON CONFLICT (product_id) DO UPDATE … gives you a "Syntax error near "DO"" in SQLite. Adding WHERE true before ON CONFLICT fixes it without filtering anything.

Overwriting the stock instead of adding to it

SET stock = excluded.stock writes just the delivered quantity into the field, and the old stock is lost. The exercise says "After your changes: The check shows the right number of rows and columns, but not every value matches." To add, include the old value: stock + excluded.stock.

Using the source column name with excluded

excluded has the columns of the target table, not those of goods_in. There is no excluded.quantity, so the exercise reports: "excluded.quantity": this column exists, but not in the table before the dot. The right name is excluded.stock, because that is the column the quantity was meant to go into.

A conflict on a column without a key

ON CONFLICT (name) only works if name has a UNIQUE index. Otherwise the database reports "ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint".

Syntax from another database

ON DUPLICATE KEY UPDATE is MySQL. SQLite doesn't know it, and the exercise reports a syntax error near "DUPLICATE".

UPSERT in MySQL, PostgreSQL, SQL Server and SQLite

There is no single upsert syntax; every database has its own. Here is the delivery from the second exercise in each:

DatabaseSyntax and details
SQLite (these exercises)INSERT … ON CONFLICT (product_id) DO UPDATE SET stock = stock + excluded.stock since version 3.24.0 (June 2018); several ON CONFLICT clauses in a row since 3.35.0; INSERT … SELECT needs a WHERE. Plus INSERT OR IGNORE and INSERT OR REPLACE.
PostgreSQLThe same form with EXCLUDED, since version 9.5. With DO UPDATE the conflict column in parentheses is required. The docs guarantee that exactly one of the two outcomes happens, insert or update, even under heavy concurrent use. If one statement would hit the same row twice, it fails with an error.
MySQLINSERT INTO products (…) VALUES (…) AS new ON DUPLICATE KEY UPDATE stock = stock + new.stock; The row alias (AS new) arrived in 8.0.19; the older VALUES(column) function is deprecated as of 8.0.20. REPLACE deletes the old row, just like in SQLite.
SQL ServerMERGE products AS t USING goods_in AS g ON t.product_id = g.product_id WHEN MATCHED THEN UPDATE SET t.stock = t.stock + g.quantity WHEN NOT MATCHED THEN INSERT (product_id, name, category, price, stock) VALUES (g.product_id, g.name, g.category, g.price, g.quantity); The closing semicolon is required. If several source rows match one target row, MERGE fails with an error. For concurrent use, Microsoft points to the HOLDLOCK table hint to prevent duplicate key violations.

Sources: sqlite.org (UPSERT, ON CONFLICT clause), PostgreSQL documentation (INSERT, 9.5 release notes), MySQL Reference Manual (INSERT … ON DUPLICATE KEY UPDATE, REPLACE), Microsoft Learn (MERGE).

FAQ

What does upsert mean?

It blends UPDATE and INSERT: update the row if it exists, insert it otherwise. None of the four databases has a command literally called UPSERT; the term covers ON CONFLICT, ON DUPLICATE KEY UPDATE and MERGE.

Why not SELECT first, then INSERT or UPDATE?

You can, but it takes two or three statements, and between checking and writing another user may create the same row. An upsert is a single statement. PostgreSQL explicitly guarantees that it ends in either an insert or an update.

What is excluded?

Think of it as a one-row table holding the row you tried to insert, the one the conflict kept out. It has the column names of the target table. In MySQL the alias after AS plays the same role.

When is INSERT OR REPLACE fine?

When you really supply every column, for example when you reload a whole table from another system. As soon as some columns are only maintained in the database, like manager or stock here, they get lost.

Done: back to the overview or on to the final test

Recursive queries and upserts complete the bonus level. The overview shows every topic and what you have already mastered. Once levels 1 to 6 are done, the final test shows what has stuck.

SQL overview Take the final test

Write to us

Choose language

Select your preferred language