MERGE, Upserts and RETURNING: Insert-or-Update in One Statement
How to insert a row or update it if it exists: ON CONFLICT and EXCLUDED, MySQL's ON DUPLICATE KEY UPDATE, MERGE with MATCHED, NOT MATCHED and NOT MATCHED BY SOURCE, RETURNING and OUTPUT, data-modifying CTEs, and concurrency.
kvi5hnuCode Sprout team member13 min readOn this page
A common task doesn't fit neatly into INSERT or UPDATE: "store this row; if it already exists, update it instead". A page view counter adds 1 to an existing page or creates the page. A nightly feed updates the products it knows about, adds new ones and removes discontinued ones. A settings screen saves a user's preferences whether or not they've saved them before.
Doing this with separate statements, "check if the row exists, then insert or update", is longer, slower, and wrong under concurrency: two sessions can both see "doesn't exist" and both try to insert. This article covers the single-statement solutions: the upsert (INSERT ... ON CONFLICT and its MySQL equivalent), the standard MERGE statement, and RETURNING, which hands back the rows that a statement changed.
RETURNING: getting changed rows back
RETURNING is used throughout this article, so it comes first. Added to an INSERT, UPDATE or DELETE, it makes the statement return rows, like a SELECT, showing the rows it changed:
CREATE TABLE tickets (
ticket_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
subject TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'open'
);
-- INSERT ... RETURNING hands back generated values
INSERT INTO tickets (subject)
VALUES ('Tent pole cracked'), ('Wrong size socks'), ('Late delivery')
RETURNING ticket_id, subject, status;
-- UPDATE ... RETURNING shows the rows as they are after the change
UPDATE tickets
SET status = 'closed'
WHERE subject LIKE '%socks%'
RETURNING ticket_id, status;
-- DELETE ... RETURNING shows what was removed
DELETE FROM tickets
WHERE status = 'closed'
RETURNING *;
ticket_id | subject | status
-----------+-------------------+--------
1 | Tent pole cracked | open
2 | Wrong size socks | open
3 | Late delivery | open
(3 rows)
ticket_id | status
-----------+--------
2 | closed
(1 row)
ticket_id | subject | status
-----------+------------------+--------
2 | Wrong size socks | closed
(1 row)
INSERT ... RETURNINGreturns the inserted rows, including values the database generated: identity numbers and defaults. This is the standard way to find the ID of a new row. Without it, the application has to run a second query, which can pick up another session's row by mistake.UPDATE ... RETURNINGreturns the rows after the change.DELETE ... RETURNINGreturns the deleted rows, as they were.RETURNING *returns every column.
Support:
| Database | Syntax |
|---|---|
| PostgreSQL | RETURNING on INSERT, UPDATE, DELETE and, since 17, MERGE |
| SQLite 3.35+ | RETURNING on INSERT, UPDATE and DELETE |
| MariaDB 10.5+ | RETURNING on INSERT and DELETE |
| SQL Server | OUTPUT inserted.col, deleted.col, placed before VALUES or WHERE |
| Oracle | RETURNING ... INTO variables, in PL/SQL |
| MySQL | no RETURNING. Use LAST_INSERT_ID() after an insert |
PostgreSQL 18 added OLD and NEW to RETURNING, so an UPDATE can return both the before and after values: RETURNING old.price, new.price. SQL Server's OUTPUT deleted.price, inserted.price has long done the same.
Upsert with INSERT ... ON CONFLICT
PostgreSQL (since 9.5) and SQLite (since 3.24) extend INSERT with an ON CONFLICT clause that says what to do when a row would violate a unique constraint or primary key:
CREATE TABLE page_hits (
page TEXT PRIMARY KEY,
hits INTEGER NOT NULL,
first_seen DATE NOT NULL
);
INSERT INTO page_hits VALUES ('/home', 10, DATE '2026-04-01');
-- Without a conflict clause, a duplicate key is an error
INSERT INTO page_hits VALUES ('/home', 1, DATE '2026-04-02');
-- DO NOTHING: skip rows whose key already exists
INSERT INTO page_hits VALUES ('/home', 1, DATE '2026-04-02'), ('/tents', 1, DATE '2026-04-02')
ON CONFLICT (page) DO NOTHING;
-- DO UPDATE: add to the existing row; EXCLUDED is the row that was proposed
INSERT INTO page_hits VALUES ('/home', 1, DATE '2026-04-03'), ('/packs', 1, DATE '2026-04-03')
ON CONFLICT (page) DO UPDATE
SET hits = page_hits.hits + EXCLUDED.hits;
SELECT * FROM page_hits ORDER BY page;
psql:/workspace/solution.sql:9: ERROR: duplicate key value violates unique constraint "page_hits_pkey"
DETAIL: Key (page)=(/home) already exists.
page | hits | first_seen
--------+------+------------
/home | 11 | 2026-04-01
/packs | 1 | 2026-04-03
/tents | 1 | 2026-04-02
(3 rows)
- Without
ON CONFLICT, inserting an existing key is an error, and the whole statement fails. ON CONFLICT (page) DO NOTHINGskips the rows whose key already exists and inserts the rest./tentswas added, and/homewas left alone. It's the "insert if absent" or "ignore duplicates" operation.ON CONFLICT (page) DO UPDATE SET ...updates the existing row instead. The special table nameEXCLUDEDrefers to the row that was proposed for insertion, and the table's own name refers to the existing row.page_hits.hits + EXCLUDED.hitsadds the new hit to the stored count, so/homewent from 10 to 11./packsdidn't exist, so it was inserted normally.
Notice that first_seen for /home stayed 1 April: DO UPDATE changes only the columns in its SET. Choosing what to keep from the old row and what to take from the new one is the main design decision in an upsert.
Details:
- The conflict target,
(page), names the columns of a unique constraint or index. It's required forDO UPDATEand optional forDO NOTHING.ON CONFLICT ON CONSTRAINT namenames the constraint directly. DO UPDATEcan have aWHERE:DO UPDATE SET price = EXCLUDED.price WHERE products.price <> EXCLUDED.priceskips the update when nothing changed.- With
RETURNING, an upsert returns the inserted or updated rows, but not rows skipped byDO NOTHING. - The conflict check is atomic: PostgreSQL guarantees an insert or an update even when other sessions are inserting the same key at the same moment. That's the main advantage over check-then-insert code.
SQLite uses the same syntax. It also has the older INSERT OR IGNORE and INSERT OR REPLACE. Beware that OR REPLACE deletes the existing row and inserts a new one, so columns you don't supply lose their values, and ON DELETE actions fire.
MySQL: ON DUPLICATE KEY UPDATE
MySQL and MariaDB have their own upsert syntax:
INSERT INTO page_hits (page, hits, first_seen)
VALUES ('/home', 1, '2026-04-03'), ('/packs', 1, '2026-04-03') AS new
ON DUPLICATE KEY UPDATE hits = page_hits.hits + new.hits;
AS new(MySQL 8.0.19+) names the proposed row, like PostgreSQL'sEXCLUDED. Older code uses theVALUES(hits)function, which is deprecated.- There's no conflict target: the update happens if the row conflicts with any unique index or primary key. On a table with several unique indexes, that can update a different row than you expect.
INSERT IGNOREskips duplicate rows, likeDO NOTHING, but it also turns many other errors into warnings, such as invalid values, which can hide bad data.REPLACE INTOdeletes and reinserts, with the same problems as SQLite'sOR REPLACE.
MERGE
MERGE is the SQL standard's statement for combining a set of source rows with a target table. It's supported by Oracle (since 9i), SQL Server (since 2008), DB2, Snowflake, BigQuery and PostgreSQL (since 15). MySQL, MariaDB and SQLite don't have it.
MERGE INTO target
USING source
ON join_condition
WHEN MATCHED [AND condition] THEN
UPDATE SET ... | DELETE
WHEN NOT MATCHED [AND condition] THEN
INSERT (...) VALUES (...)
MERGE joins the source to the target. Each source row either matches a target row or doesn't, and the WHEN clauses say what to do in each case. The source can be a table, a view or a subquery.
The next example applies a supplier's nightly feed to products. The feed has four rows: a new price and stock for the head torch, the lantern marked as discontinued, a restock of the Day 18 backpack, and a new product, trek poles:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Tonight's feed from the supplier: prices and stock, keyed by product_id
CREATE TABLE supplier_feed (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
discontinued BOOLEAN NOT NULL DEFAULT false
);
INSERT INTO supplier_feed VALUES
(3, 'Glow head torch', 'lighting', 36.00, 50, false), -- new price and stock
(4, 'Basecamp lantern', 'lighting', 27.00, 15, true), -- discontinued
(6, 'Day 18 backpack', 'packs', 54.00, 10, false), -- restocked
(8, 'Trek poles', 'hiking', 59.00, 18, false); -- new product
-- Apply the feed: update, delete or insert, depending on each row
MERGE INTO products p
USING supplier_feed f
ON f.product_id = p.product_id
WHEN MATCHED AND f.discontinued THEN
DELETE
WHEN MATCHED THEN
UPDATE SET price = f.price, stock = f.stock
WHEN NOT MATCHED AND NOT f.discontinued THEN
INSERT (product_id, name, category, price, stock)
VALUES (f.product_id, f.name, f.category, f.price, f.stock)
RETURNING merge_action() AS action, p.product_id, p.name, p.price, p.stock;
SELECT product_id, name, price, stock FROM products ORDER BY product_id;
action | product_id | name | price | stock
--------+------------+------------------+-------+-------
UPDATE | 3 | Glow head torch | 36.00 | 50
DELETE | 4 | Basecamp lantern | 27.00 | 15
UPDATE | 6 | Day 18 backpack | 54.00 | 10
INSERT | 8 | Trek poles | 59.00 | 18
(4 rows)
product_id | name | price | stock
------------+-------------------+--------+-------
1 | Ridge 2 tent | 249.99 | 12
2 | Summit 4 tent | 489.00 | 3
3 | Glow head torch | 36.00 | 50
5 | Trail 30 backpack | 89.95 | 22
6 | Day 18 backpack | 54.00 | 10
7 | Merino socks | 16.00 | 75
8 | Trek poles | 59.00 | 18
(7 rows)
- The torch and the backpack match and aren't discontinued, so the second
WHEN MATCHEDupdates them. - The lantern matches and is discontinued, so the first
WHEN MATCHEDdeletes it. - The trek poles don't match any product, so
WHEN NOT MATCHEDinserts them. - Products not in the feed (the tents, the Trail 30 backpack and the socks) are untouched.
WHEN clauses are checked in order, and the first one whose condition is true is applied. That's why the discontinued case comes before the general WHEN MATCHED: in the other order, the unconditional update would catch the lantern first. A row that no WHEN clause applies to is left alone.
PostgreSQL 17's merge_action() function, used in RETURNING, reports what happened to each row: INSERT, UPDATE or DELETE. SQL Server has the same with OUTPUT $action.
WHEN NOT MATCHED BY SOURCE
The basic MERGE only acts on target rows that the source mentions. To make a table mirror a source exactly, you also need to handle target rows that the source doesn't contain:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Tonight's feed from the supplier: prices and stock, keyed by product_id
CREATE TABLE supplier_feed (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
discontinued BOOLEAN NOT NULL DEFAULT false
);
INSERT INTO supplier_feed VALUES
(3, 'Glow head torch', 'lighting', 36.00, 50, false), -- new price and stock
(4, 'Basecamp lantern', 'lighting', 27.00, 15, true), -- discontinued
(6, 'Day 18 backpack', 'packs', 54.00, 10, false), -- restocked
(8, 'Trek poles', 'hiking', 59.00, 18, false); -- new product
-- A small table that must mirror the feed exactly
CREATE TABLE feed_mirror (product_id INTEGER PRIMARY KEY, price DECIMAL(8, 2) NOT NULL);
INSERT INTO feed_mirror VALUES (3, 34.50), (5, 89.95), (6, 54.00);
MERGE INTO feed_mirror m
USING supplier_feed f
ON f.product_id = m.product_id
WHEN MATCHED AND m.price <> f.price THEN
UPDATE SET price = f.price
WHEN NOT MATCHED THEN -- in the feed, not in the mirror
INSERT VALUES (f.product_id, f.price)
WHEN NOT MATCHED BY SOURCE THEN -- in the mirror, not in the feed
DELETE
RETURNING merge_action() AS action, m.product_id, m.price;
SELECT * FROM feed_mirror ORDER BY product_id;
action | product_id | price
--------+------------+-------
UPDATE | 3 | 36.00
DELETE | 5 | 89.95
INSERT | 8 | 59.00
INSERT | 4 | 27.00
(4 rows)
product_id | price
------------+-------
3 | 36.00
4 | 27.00
6 | 54.00
8 | 59.00
(4 rows)

- Product 3's price changed, so it's updated. Product 6 matches but has the same price, so the
AND m.price <> f.pricecondition skips it: no needless write. - Products 4 and 8 are in the feed but not the mirror (
NOT MATCHED, short forNOT MATCHED BY TARGET), so they're inserted. - Product 5 is in the mirror but not the feed (
NOT MATCHED BY SOURCE), so it's deleted.
WHEN NOT MATCHED BY SOURCE arrived in PostgreSQL 17, and SQL Server has had it since 2008. Oracle doesn't support it, so there you need a separate DELETE ... WHERE NOT EXISTS.
MERGE versus ON CONFLICT
INSERT ... ON CONFLICT | MERGE | |
|---|---|---|
| Standard | no (PostgreSQL, SQLite) | yes |
| Actions | insert, or update / do nothing on conflict | insert, update and delete, with conditions |
| Rows absent from the source | not handled | NOT MATCHED BY SOURCE (PostgreSQL 17, SQL Server) |
| Needs a unique constraint | yes, it detects conflicts through one | no, matching uses any join condition |
| Concurrent inserts of the same key | safe: always inserts or updates | can fail with a unique violation |
In PostgreSQL, use ON CONFLICT for a simple upsert of individual rows, especially from many concurrent sessions, and MERGE for applying a batch of changes with several kinds of action. MERGE follows the normal isolation rules, so if another session inserts a matching row after MERGE has decided a row is "not matched", the insert fails. In SQL Server, MERGE has the same problem, plus a history of bugs, and experienced developers usually add the HOLDLOCK hint (MERGE INTO target WITH (HOLDLOCK) ...) or use separate UPDATE and INSERT statements in a transaction.
A target row may change only once
Both statements refuse to change the same target row twice in one statement:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- The same key twice in the source: MERGE refuses to change a row twice
CREATE TABLE price_updates (product_id INTEGER, price DECIMAL(8, 2));
INSERT INTO price_updates VALUES (3, 35.00), (3, 36.00);
MERGE INTO products p
USING price_updates u ON u.product_id = p.product_id
WHEN MATCHED THEN UPDATE SET price = u.price;
-- ON CONFLICT has the same rule
INSERT INTO products (product_id, name, category, price, stock)
VALUES (3, 'Glow head torch', 'lighting', 35.00, 40),
(3, 'Glow head torch', 'lighting', 36.00, 40)
ON CONFLICT (product_id) DO UPDATE SET price = EXCLUDED.price;
SELECT product_id, price FROM products WHERE product_id = 3;
psql:/workspace/solution.sql:68: ERROR: MERGE command cannot affect row a second time
HINT: Ensure that not more than one source row matches any one target row.
psql:/workspace/solution.sql:74: ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
HINT: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.
product_id | price
------------+-------
3 | 34.50
(1 row)
The source has two new prices for product 3. Which should win? Rather than choose arbitrarily, as UPDATE ... FROM does (article 32), MERGE and ON CONFLICT DO UPDATE raise an error, and the price stays 34.50. Remove duplicates from the source first, for example with DISTINCT ON or ROW_NUMBER() (articles 10 and 27) to keep the latest value per key (articles 27 and 33).
Data-modifying CTEs
In PostgreSQL, a CTE can contain an INSERT, UPDATE, DELETE or MERGE with RETURNING, and the rest of the statement can use the returned rows. This makes it possible to chain changes in a single statement, such as moving rows from one table to another:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
CREATE TABLE order_archive (LIKE orders);
-- Move the cancelled orders (and their lines) in one statement:
-- DELETE ... RETURNING feeds the INSERT
WITH removed_lines AS (
DELETE FROM order_items
WHERE order_id IN (SELECT order_id FROM orders WHERE status = 'cancelled')
),
moved AS (
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING *
)
INSERT INTO order_archive
SELECT * FROM moved;
SELECT * FROM order_archive;
SELECT COUNT(*) AS orders_left FROM orders;
order_id | customer_id | placed_on | status
----------+-------------+------------+-----------
105 | 4 | 2026-03-20 | cancelled
(1 row)
orders_left
-------------
5
(1 row)
The moved CTE deletes the cancelled orders and returns them, and the main INSERT copies the returned rows into the archive. The removed_lines CTE deletes the cancelled orders' lines in the same statement. Because the whole statement is atomic, the orders can't end up both deleted and not archived, or archived twice.
Some rules make data-modifying CTEs different from ordinary ones:
- Every data-modifying CTE is executed exactly once, completely, even if the main query doesn't use its output.
- All parts of the statement see the same snapshot of the data, from before the statement started. A CTE can't see another CTE's changes by reading the table, only through its
RETURNINGoutput. That's why the CTE deleting the order lines works out which orders to clear with its own subquery onorders. - Foreign keys are checked at the end of the statement, so deleting the orders and their lines in two CTEs works, whatever order PostgreSQL runs them in.
- Don't modify the same row in two parts of one statement: the result is unpredictable.
CREATE TABLE order_archive (LIKE orders) in the example creates an empty table with the same columns as orders, a PostgreSQL shortcut (MySQL: CREATE TABLE order_archive LIKE orders). SQL Server can chain changes with OUTPUT ... INTO another_table, and other databases need separate statements in a transaction.
What's current
- PostgreSQL 17 added
RETURNINGtoMERGEwith themerge_action()function,WHEN NOT MATCHED BY SOURCE, andMERGEon updatable views. - PostgreSQL 18 added
OLDandNEWinRETURNING, so one statement can return values from before and after the change. - MySQL 8.0.19 introduced row aliases (
VALUES (...) AS new) forON DUPLICATE KEY UPDATE, replacing the deprecatedVALUES()function. MySQL still has neitherMERGEnorRETURNING. - SQLite 3.35 added
RETURNING. SQLite's upsert has existed since 3.24.
Common questions
What's an upsert? "Update or insert": a single operation that inserts a row, or updates it if a row with the same key already exists.
Why not check whether the row exists and then insert or update?
Two sessions can run the check at the same time, both see no row, and both insert, so one fails with a duplicate key error or, without a unique constraint, creates a duplicate. ON CONFLICT handles this atomically.
What's EXCLUDED?
In ON CONFLICT DO UPDATE, the row that would have been inserted. The table's name (or alias) refers to the existing row.
Does ON CONFLICT work without a unique constraint?
No. It detects conflicts through a unique index or constraint on the conflict target columns.
Should I use MERGE or ON CONFLICT in PostgreSQL?
ON CONFLICT for concurrent single-row upserts, MERGE for applying a batch of changes that include updates, inserts and deletes.
How do I get the ID of a newly inserted row?
RETURNING id in PostgreSQL, SQLite and MariaDB, OUTPUT inserted.id in SQL Server, LAST_INSERT_ID() in MySQL, and RETURNING id INTO variable in Oracle PL/SQL.
Why did my MERGE fail with "cannot affect row a second time"?
Two source rows matched the same target row. Remove the duplicates from the source first.
Summary
RETURNINGmakesINSERT,UPDATE,DELETEand, in PostgreSQL 17,MERGEreturn the rows they changed, including generated values. SQL Server usesOUTPUT.INSERT ... ON CONFLICT (key) DO NOTHING | DO UPDATE SET ...is PostgreSQL's and SQLite's atomic upsert.EXCLUDEDholds the proposed row.- MySQL uses
ON DUPLICATE KEY UPDATE, with a row alias for the new values. MERGEjoins a source to a target and appliesWHEN MATCHED,WHEN NOT MATCHEDandWHEN NOT MATCHED BY SOURCEactions, with optional conditions, in order.- Both
MERGEandON CONFLICT DO UPDATErefuse to change a target row twice. Remove duplicates from the source first. - For concurrent single-row upserts,
ON CONFLICTis safer thanMERGE. - PostgreSQL's data-modifying CTEs chain changes, such as moving rows, in one atomic statement.
Practice questions
Write an upsert that records that customer 1 has a preferred currency of 'EUR' in a table preferences(customer_id PRIMARY KEY, currency), replacing any existing preference.
Answer
INSERT INTO preferences (customer_id, currency)
VALUES (1, 'EUR')
ON CONFLICT (customer_id) DO UPDATE
SET currency = EXCLUDED.currency;
In MySQL: INSERT INTO preferences (customer_id, currency) VALUES (1, 'EUR') AS new ON DUPLICATE KEY UPDATE currency = new.currency;
In the page_hits example, change the upsert so that it also keeps the earlier of the two first_seen dates.
Answer
INSERT INTO page_hits VALUES ('/home', 1, DATE '2026-03-15')
ON CONFLICT (page) DO UPDATE
SET hits = page_hits.hits + EXCLUDED.hits,
first_seen = LEAST(page_hits.first_seen, EXCLUDED.first_seen);
LEAST returns the smaller of its arguments, here 15 March.
In the feed MERGE, what would happen to the lantern if the two WHEN MATCHED clauses were swapped?
Answer
The unconditional WHEN MATCHED THEN UPDATE would come first and apply to every matching row, including the lantern, so the lantern would be updated rather than deleted. The WHEN MATCHED AND f.discontinued THEN DELETE clause would never be reached. Put the more specific clauses first.
Why might INSERT ... ON CONFLICT DO NOTHING RETURNING id return fewer rows than were in the VALUES list?
Answer
Rows skipped because of a conflict aren't inserted, so they aren't returned. If you need the IDs of the existing rows as well, select them separately, for example by running a SELECT for the keys that weren't returned, or use DO UPDATE with a no-op SET, which returns the existing rows but writes them again.
A nightly job must make table prices match the table price_feed exactly: update changed prices, add new products and remove products no longer in the feed. Which statement can do this in one step in PostgreSQL 17?
Answer
MERGE with three clauses:
MERGE INTO prices p
USING price_feed f ON f.product_id = p.product_id
WHEN MATCHED AND p.price <> f.price THEN UPDATE SET price = f.price
WHEN NOT MATCHED THEN INSERT (product_id, price) VALUES (f.product_id, f.price)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
ON CONFLICT can't delete rows that are missing from the source.
Previous: Deleting Rows: DELETE, TRUNCATE and Removing Duplicates
Next: SQL Data Types: Numbers, Text, Dates, Booleans and CAST

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.