Inserting, Updating and Deleting · Lesson 38 of 64

SQL Upsert: Insert or Update

What you will learn

  • What an upsert is
  • How ON CONFLICT ... DO NOTHING skips a duplicate
  • How ON CONFLICT ... DO UPDATE and excluded update an existing row
  • Why INSERT OR REPLACE is more dangerous

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The changes happen only in your browser's copy of the data; Reset data puts everything back. Run the cells from top to bottom.

1. The problem

Imagine loading a list of prices that arrives every day. Some products are new, and some already exist with an old price. If you INSERT a product that exists, you get a UNIQUE error (lesson 5.1). If you UPDATE a product that does not exist, nothing happens. An upsert does the right thing for both: insert the row if it is new, update it if it exists.

An upsert needs a column (or columns) with a UNIQUE or primary key rule, so the database can tell that the row "already exists". That rule is called the conflict target.

2. DO NOTHING

ON CONFLICT (column) DO NOTHING skips a row that would break the unique rule, without an error:

products.sku is unique. The first row is new, the second repeats an existing sku (SKU-0001):

INSERT INTO products (sku, name, category_id, supplier_id, price, cost, added_on)
VALUES ('SKU-8001', 'Brand new lamp', 1, 1, 20.0, 9.0, '2026-10-05'),
       ('SKU-0001', 'Duplicate pan', 1, 1, 99.0, 9.0, '2026-10-05')
ON CONFLICT (sku) DO NOTHING;
(1 row changed)
SELECT sku, name, price FROM products WHERE sku IN ('SKU-8001', 'SKU-0001') ORDER BY sku;
sku       name            price
--------  --------------  -----
SKU-0001  Steel pan         6.6
SKU-8001  Brand new lamp   20.0
(2 rows)

branches.name is unique. The first row is new, the second repeats Central:

INSERT INTO branches (name, city) VALUES ('Parkside', 'Rome'), ('Central', 'Oslo')
ON CONFLICT (name) DO NOTHING;
(1 row changed)
SELECT branch_id, name, city FROM branches WHERE name IN ('Parkside', 'Central') ORDER BY name;
branch_id  name      city
---------  --------  ------
        1  Central   Lisbon
        7  Parkside  Rome
(2 rows)

courses.code is unique. The first row is new, the second repeats MATH101:

INSERT INTO courses (code, title, department_id, credits)
VALUES ('ART101', 'Drawing', 1, 2), ('MATH101', 'Duplicate algebra', 1, 2)
ON CONFLICT (code) DO NOTHING;
(0 rows changed)
SELECT code, title, credits FROM courses WHERE code IN ('ART101', 'MATH101') ORDER BY code;
code     title                   credits
-------  ----------------------  -------
ART101   Drawing                       2
MATH101  Foundations of Algebra        4
(2 rows)

Only the new row was added; the existing row is unchanged and there was no error. This is a safe way to run a load twice (it will not add duplicates).

3. DO UPDATE and excluded

DO UPDATE SET column = value changes the existing row instead. The special name excluded refers to the row you tried to insert, so you can copy its values:

Load a price list: the existing sku gets its price updated, and a new sku is added:

INSERT INTO products (sku, name, category_id, supplier_id, price, cost, added_on)
VALUES ('SKU-0001', 'Steel pan', 1, 1, 8.25, 3.96, '2026-10-05'),
       ('SKU-8002', 'Brand new mug', 1, 1, 6.5, 2.0, '2026-10-05')
ON CONFLICT (sku) DO UPDATE SET price = excluded.price;
(2 rows changed)
SELECT sku, name, price FROM products WHERE sku IN ('SKU-0001', 'SKU-8002') ORDER BY sku;
sku       name           price
--------  -------------  -----
SKU-0001  Steel pan       8.25
SKU-8002  Brand new mug    6.5
(2 rows)

Move the city of an existing branch and add a new one:

INSERT INTO branches (name, city) VALUES ('Central', 'Oslo'), ('Marina', 'Cairo')
ON CONFLICT (name) DO UPDATE SET city = excluded.city;
(2 rows changed)
SELECT branch_id, name, city FROM branches WHERE name IN ('Central', 'Marina') ORDER BY name;
branch_id  name     city
---------  -------  -----
        1  Central  Oslo
        8  Marina   Cairo
(2 rows)

Change the credits of an existing course and add a new one:

INSERT INTO courses (code, title, department_id, credits)
VALUES ('MATH101', 'Foundations of Algebra', 1, 6), ('MUS101', 'Music Basics', 1, 2)
ON CONFLICT (code) DO UPDATE SET credits = excluded.credits;
(2 rows changed)
SELECT code, title, credits FROM courses WHERE code IN ('MATH101', 'MUS101') ORDER BY code;
code     title                   credits
-------  ----------------------  -------
MATH101  Foundations of Algebra        6
MUS101   Music Basics                  2
(2 rows)

You choose which columns to update, so the other columns of the existing row stay as they were. The statement can also use the old value: SET stock = stock + excluded.stock adds the incoming quantity to the existing one.

4. A counter with an upsert

A classic use is a counter: insert 1 the first time, add 1 every time after:

CREATE TABLE visits (page TEXT PRIMARY KEY, hits INTEGER NOT NULL);
INSERT INTO visits (page, hits) VALUES ('home', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
INSERT INTO visits (page, hits) VALUES ('home', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
INSERT INTO visits (page, hits) VALUES ('about', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
SELECT page, hits FROM visits ORDER BY page;
page   hits
-----  ----
about     1
home      2
(2 rows)
CREATE TABLE visits (page TEXT PRIMARY KEY, hits INTEGER NOT NULL);
INSERT INTO visits (page, hits) VALUES ('home', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
INSERT INTO visits (page, hits) VALUES ('home', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
INSERT INTO visits (page, hits) VALUES ('about', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
SELECT page, hits FROM visits ORDER BY page;
page   hits
-----  ----
about     1
home      2
(2 rows)
CREATE TABLE visits (page TEXT PRIMARY KEY, hits INTEGER NOT NULL);
INSERT INTO visits (page, hits) VALUES ('home', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
INSERT INTO visits (page, hits) VALUES ('home', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
INSERT INTO visits (page, hits) VALUES ('about', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;
SELECT page, hits FROM visits ORDER BY page;
page   hits
-----  ----
about     1
home      2
(2 rows)

5. INSERT OR REPLACE: use with care

SQLite also has a shorter form, INSERT OR REPLACE. When the row exists, it deletes the old row and inserts a new one. Columns you did not mention are reset to their defaults, and the row may lose links. An upsert with DO UPDATE changes only the columns you name, so it is usually the safer choice:

CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT, city TEXT);
INSERT INTO members VALUES (1, 'Rina', 'Dhaka');
INSERT OR REPLACE INTO members (id, name) VALUES (1, 'Rina A.');
SELECT id, name, city FROM members;
id  name     city
--  -------  ----
 1  Rina A.  NULL
(1 row)
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT, city TEXT);
INSERT INTO members VALUES (1, 'Rina', 'Dhaka');
INSERT OR REPLACE INTO members (id, name) VALUES (1, 'Rina A.');
SELECT id, name, city FROM members;
id  name     city
--  -------  ----
 1  Rina A.  NULL
(1 row)
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT, city TEXT);
INSERT INTO members VALUES (1, 'Rina', 'Dhaka');
INSERT OR REPLACE INTO members (id, name) VALUES (1, 'Rina A.');
SELECT id, name, city FROM members;
id  name     city
--  -------  ----
 1  Rina A.  NULL
(1 row)

The city was lost: NULL. With ON CONFLICT (id) DO UPDATE SET name = excluded.name the city would have stayed.

In other databases. PostgreSQL also uses INSERT ... ON CONFLICT (...) DO NOTHING or DO UPDATE SET ... = EXCLUDED.... (its documentation calls it an upsert and says it is a PostgreSQL extension to standard SQL). MySQL writes it differently: INSERT ... ON DUPLICATE KEY UPDATE ... for the update case, and INSERT IGNORE to skip errors, according to its documentation. SQLite's ON CONFLICT form was added in version 3.24.0. All of this is from the official documentation and was not run here.

Worked example: loading a daily price file

A supplier sends a file with sku and price every day.

Task Statement
new skus must be added INSERT ... ON CONFLICT (sku) ...
known skus must get the new price DO UPDATE SET price = excluded.price
known skus must be left alone DO NOTHING

Load the file into a staging table first (lesson 5.8), check it, then upsert from the staging table with INSERT ... SELECT ... ON CONFLICT. The file is made up.

Common mistakes

  • No unique rule on the conflict column, so the database cannot detect the conflict.
  • INSERT OR REPLACE when you meant to change one column.
  • Updating columns you did not mean to in DO UPDATE.
  • Forgetting that excluded.x is the new value and x is the old one.
  • Assuming the same syntax everywhere.

Key takeaways

  • An upsert inserts a new row or updates an existing one in one statement.
  • ON CONFLICT (col) DO NOTHING skips duplicates; DO UPDATE SET ... = excluded.... updates them.
  • It needs a UNIQUE or primary key rule on the conflict column.
  • INSERT OR REPLACE deletes and re-inserts the row, so unmentioned columns are lost.

Practice

1. What does ON CONFLICT (email) DO NOTHING do?

Show answer

If a row with that email already exists, the new row is skipped without an error.

2. What does excluded.price mean?

Show answer

The price value of the row you tried to insert (the incoming value).

3. Which columns does DO UPDATE SET price = excluded.price change?

Show answer

Only price; the other columns of the existing row stay as they were.

4. Why can INSERT OR REPLACE lose data?

Show answer

It deletes the existing row and inserts a new one, so columns you did not list are reset.

5. What does an upsert need in the table?

Show answer

A UNIQUE constraint or primary key on the conflict column.

6. Write the upsert for a counter table visits(page, hits).

Show answer

INSERT INTO visits (page, hits) VALUES ('home', 1) ON CONFLICT (page) DO UPDATE SET hits = hits + 1;