SQLite UPSERT
What is UPSERT?
Sometimes you want to insert a record, but the record might already be in the table. If you insert it again, you get an error.
UPSERT solves this. It inserts the record if it is new, and updates it (or does nothing) if it already exists. The name comes from UPdate and inSERT.
The Problem
There is already a shipper with ShipperID 1. Inserting another record with the same ShipperID gives an error:
Example
INSERT INTO Shippers (ShipperID, ShipperName, Phone)
VALUES (1, 'Speedy Express', '(503) 555-0000');
Try it Yourself »
ON CONFLICT DO UPDATE
Add ON CONFLICT to say what should happen instead. This example updates the phone number when the ShipperID already exists:
Example
INSERT INTO Shippers (ShipperID, ShipperName, Phone)
VALUES (1, 'Speedy Express', '(503) 555-0000')
ON CONFLICT (ShipperID)
DO UPDATE SET Phone = excluded.Phone;
Try it Yourself »
excluded is a special name for the record you tried to insert. You must write exactly excluded, and it only works inside DO UPDATE. excluded.Phone is the new phone number.
The conflict column must have a PRIMARY KEY or a UNIQUE constraint.
Note: UPSERT works in SQLite 3.24.0 and later.
ON CONFLICT DO NOTHING
DO NOTHING skips the new record if it already exists, without an error:
Example
INSERT INTO Shippers (ShipperID, ShipperName, Phone)
VALUES (1, 'Speedy Express', '(503) 555-0000')
ON CONFLICT DO NOTHING;
Try it Yourself »
INSERT OR IGNORE and INSERT OR REPLACE
SQLite also has an older, shorter syntax:
INSERT OR IGNOREskips the new record if it breaks a rule, likeDO NOTHINGINSERT OR REPLACEdeletes the old record, and inserts the new one
Example
INSERT OR REPLACE INTO Shippers
(ShipperID, ShipperName, Phone)
VALUES (1, 'Speedy Express', '(503) 555-0000');
Try it Yourself »
Warning: INSERT OR REPLACE deletes the old record first. Columns that you do not give a value for get NULL, or their default value, and not the old value.
Note: REPLACE INTO is a short way of writing INSERT OR REPLACE INTO.