18. UPSERT and RETURNING

"Add it, or if it is already there, update it" is one of the commonest jobs in a program. SQL does it in one statement, and RETURNING tells you what a change did.

When the row may already be there

Chapter 16 showed that adding a row whose key or UNIQUE value is taken fails. A program often doesn't know beforehand: the delivery list may hold both new products and ones the shop already sells; a counter's row may or may not exist yet. Instead of a SELECT first and then an INSERT or an UPDATE, SQL can say what to do when the row is already there. Adding-or-updating is called an upsert (update + insert).

INSERT OR IGNORE: skip what is there

INSERT OR IGNORE adds the rows it can and quietly skips the ones that break a rule:

INSERT OR IGNORE INTO category (name) VALUES ('Drinks'), ('Frozen');
SELECT * FROM category;
idname
1Drinks
2Bakery
3Snacks
4Stationery
5Frozen
5 rows

1 row changed: Frozen came in, Drinks was already there and was skipped, with no error.

OR IGNORE skips a row that breaks any rule (NOT NULL, UNIQUE, CHECK), not only the one you had in mind, and says nothing. A row with a mistake in it just isn't there afterwards. When you mean "skip it if the key is taken", say that with ON CONFLICT ... DO NOTHING (below).

INSERT OR REPLACE: delete, then insert

INSERT OR REPLACE (also written REPLACE INTO) sounds like "update the row that is there". It is not: when the new row clashes, the old row is deleted and the new one inserted in its place. Every column you don't give gets its default, not its old value. Watch the Pen's stock:

SELECT * FROM product WHERE id = 11;
idnamecategory_idpricestock
11Pen415.0300
1 row
INSERT OR REPLACE INTO product (id, name, category_id, price) VALUES (11, 'Pen', 4, 18);
SELECT * FROM product WHERE id = 11;
idnamecategory_idpricestock
11Pen418.00
1 row

The price became 18 as meant, but the 300 pens in stock became 0: the new row had no stock, so it took the default. Being a delete and an insert, REPLACE also sets off delete triggers (chapter 31) and foreign key actions on the old row (chapter 22).

Use REPLACE only when the new row says everything about the thing, every column. To change some columns of a row that may be there, use ON CONFLICT ... DO UPDATE.

ON CONFLICT: say exactly what to do

The upsert proper is INSERT ... ON CONFLICT (columns) DO .... The columns in brackets are the key or UNIQUE columns whose clash you expect; after DO comes what to do then.

DO NOTHING skips the row, like OR IGNORE, but only for that clash:

INSERT INTO category (name) VALUES ('Snacks') ON CONFLICT (name) DO NOTHING;
✓ 0 rows changed

No row changed, no error. DO UPDATE SET changes the row that is there instead. A delivery comes in: Potato Chips, which the shop sells, and Rice Crackers, which it doesn't yet. Each known product gets the delivered amount added to its stock; a new one is added:

INSERT INTO product (id, name, category_id, price, stock) VALUES
  (7,  'Potato Chips',  3, 25, 50),
  (13, 'Rice Crackers', 3, 30, 40)
ON CONFLICT (id) DO UPDATE SET stock = stock + excluded.stock;
SELECT * FROM product WHERE category_id = 3;
idnamecategory_idpricestock
7Potato Chips325.0250
8Dried Mango390.045
9Cashew Nuts3150.020
13Rice Crackers330.040
4 rows

2 rows changed: the Potato Chips went from 200 to 250 and the Rice Crackers came in with 40. In DO UPDATE, a plain column name (stock) is the value of the row already there; excluded.stock is the value the INSERT tried to add (the row that was "left out").

A counter is the classic upsert. A little table counts how many times each product's page was viewed (CREATE TABLE: chapter 20):

CREATE TABLE product_view (
  product_id INTEGER PRIMARY KEY,
  views      INTEGER NOT NULL
);
✓ Done

The same statement each time someone opens a page: the first time it adds the row with 1, after that it adds 1:

INSERT INTO product_view (product_id, views) VALUES (1, 1)
ON CONFLICT (product_id) DO UPDATE SET views = views + 1;
INSERT INTO product_view (product_id, views) VALUES (1, 1)
ON CONFLICT (product_id) DO UPDATE SET views = views + 1;
INSERT INTO product_view (product_id, views) VALUES (5, 1)
ON CONFLICT (product_id) DO UPDATE SET views = views + 1;
INSERT INTO product_view (product_id, views) VALUES (1, 1)
ON CONFLICT (product_id) DO UPDATE SET views = views + 1;
SELECT * FROM product_view;
product_idviews
13
51
2 rows

Product 1 was viewed three times, product 5 once.

The columns in ON CONFLICT (...) must be a primary key or have a UNIQUE rule (or a unique index, chapter 25); otherwise the statement is refused. Other databases spell upsert differently (MySQL has ON DUPLICATE KEY UPDATE); SQLite's and Phai SQL's ON CONFLICT is the same as PostgreSQL's.

RETURNING: see what a change did

Add RETURNING and a list of columns at the end of an INSERT, UPDATE or DELETE, and it gives back the rows it changed, like a SELECT. The new order's number comes back in the same statement, without a last_insert_rowid() afterwards:

INSERT INTO orders (customer_id, ordered, status) VALUES (5, '2026-12-01', 'paid')
RETURNING id, customer_id, status;
idcustomer_idstatus
165paid
1 row

On an UPDATE, it gives the rows as they are after the change. Bakery up by 5 baht:

UPDATE product SET price = price + 5 WHERE category_id = 2
RETURNING id, name, price;
idnameprice
4Croissant40.0
5Banana Bread65.0
6Cheesecake125.0
3 rows

On a DELETE, it gives the rows that were deleted, a last look at them on the way out. * means every column:

DELETE FROM product_view WHERE views < 2 RETURNING *;
product_idviews
51
1 row

RETURNING works on an upsert too, and shows each row as it ended up, added or updated:

INSERT INTO product (id, name, category_id, price, stock) VALUES (1, 'Coffee', 1, 55, 30)
ON CONFLICT (id) DO UPDATE SET stock = stock + excluded.stock
RETURNING id, name, stock;
idnamestock
1Coffee150
1 row
  1. Add the categories 'Bakery' and 'Toys' so that one already there is skipped without an error, and see how many rows changed.
  2. A delivery of 20 Notebooks (id 10, 'Notebook', category 4, 30 baht) and 15 Erasers (a new product id 14, 'Eraser', category 4, 10 baht): add to the stock of what is there, add what isn't.
  3. Raise the price of every product under 20 baht by 2 baht, getting back the name and new price of each.
Show the answer
INSERT INTO category (name) VALUES ('Bakery'), ('Toys') ON CONFLICT (name) DO NOTHING;
SELECT changes();
INSERT INTO product (id, name, category_id, price, stock) VALUES
  (10, 'Notebook', 4, 30, 20),
  (14, 'Eraser',   4, 10, 15)
ON CONFLICT (id) DO UPDATE SET stock = stock + excluded.stock
RETURNING id, name, stock;
UPDATE product SET price = price + 2 WHERE price < 20 RETURNING name, price;
changes()
1
1 row
idnamestock
10Notebook95
14Eraser15
2 rows
nameprice
Pen20.0
Eraser12.0
2 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made