Upsert and MERGE

Updated · 8 min read
mediumPostgreSQL 18sqlupserton-conflictmergeinterview

An upsert inserts a row, or updates the existing row instead if one with the same key is already there. Navika's study totals keep one row per student. When she studies again, the program shouldn't have to ask "is there a row for her yet?" and then choose between INSERT and UPDATE: between the question and the answer, another session could insert the same row, and one of them would fail. An upsert does both in one statement, safely. This lesson covers PostgreSQL's INSERT ... ON CONFLICT, the standard MERGE, and how MySQL and SQL Server spell the same idea.

In One Minute

  • INSERT ... ON CONFLICT (key) DO UPDATE SET ... inserts, or updates the row that's already there.
  • EXCLUDED.column is the value the INSERT tried to insert; table.column is the value already stored.
  • ON CONFLICT DO NOTHING skips rows that would be duplicates.
  • The conflict target must have a unique constraint or primary key.
  • MERGE (standard SQL, PostgreSQL 15+) matches a whole source table: update the matches, insert the rest.

The Problem: Insert or Update?

SQL
CREATE TABLE study_totals (
  student_id INTEGER PRIMARY KEY,
  minutes    INTEGER NOT NULL
);

Navika (103) already has a row with 45 minutes. Recording 30 more with a plain INSERT fails:

SQL▶ Try it
CREATE TABLE study_totals (student_id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO study_totals VALUES (103, 45);
 
INSERT INTO study_totals VALUES (103, 30);
Output
CREATE TABLE
 
INSERT 0 1
 
ERROR:  duplicate key value violates unique constraint "study_totals_pkey"
DETAIL:  Key (student_id)=(103) already exists.

The primary key refuses a second row for her. What we want is "add 30 to her total, or start a total if she has none".

INSERT ... ON CONFLICT DO UPDATE

SQL
INSERT INTO table (columns) VALUES (...)
ON CONFLICT (key_columns) DO UPDATE SET column = value, ...;
SQL▶ Try it
CREATE TABLE study_totals (student_id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO study_totals VALUES (103, 45);
 
INSERT INTO study_totals VALUES (103, 30)
ON CONFLICT (student_id)
DO UPDATE SET minutes = study_totals.minutes + EXCLUDED.minutes;
 
INSERT INTO study_totals VALUES (101, 90)
ON CONFLICT (student_id)
DO UPDATE SET minutes = study_totals.minutes + EXCLUDED.minutes;
 
SELECT * FROM study_totals ORDER BY student_id;
Output
CREATE TABLE
 
INSERT 0 1
 
INSERT 0 1
 
INSERT 0 1
 
 student_id | minutes
------------+---------
        101 |      90
        103 |      75
(2 rows)

Two upserts, two different outcomes. For Navika, a row with student_id 103 existed, so the UPDATE ran: 45 already stored plus 30 tried gives 75. For Srihitha (101), there was no row, so the insert simply happened, with 90. EXCLUDED is the row the INSERT proposed; study_totals.minutes is the stored value. ON CONFLICT (student_id) names the unique column that defines "already exists".

Navika's row exists, so 45 + 30 = 75 is updated; Srihitha has no row, so 90 is inserted

DO NOTHING and Real Tables

ON CONFLICT DO NOTHING skips a row that would be a duplicate, without an error:

SQL▶ Try it
CREATE TABLE study_totals (student_id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL);
INSERT INTO study_totals VALUES (103, 45);
 
INSERT INTO study_totals VALUES (103, 30)
ON CONFLICT DO NOTHING;
 
SELECT * FROM study_totals;
Output
CREATE TABLE
 
INSERT 0 1
 
INSERT 0 0
 
 student_id | minutes
------------+---------
        103 |      45
(1 row)

INSERT 0 0: nothing inserted, and the stored 45 is untouched. That suits "make sure this row exists" jobs, like loading a file that may contain rows already present. Upserts work on composite keys too. Re-enrolling Srihitha in Java Basics updates her status instead of failing on the (student_id, course_id) key:

SQL▶ Try it
INSERT INTO enrollments VALUES (101, 1, '2026-01-05', 'active')
ON CONFLICT (student_id, course_id)
DO UPDATE SET status = EXCLUDED.status
RETURNING *;
Output
 student_id | course_id | enrolled_on | status
------------+-----------+-------------+--------
        101 |         1 | 2025-08-25  | active
(1 row)

Her enrolled_on stayed 2025-08-25, because SET changed only status. The conflict target must match a unique constraint or primary key exactly; ON CONFLICT (status) fails, because nothing makes status unique.

MERGE: Many Rows at Once

MERGE compares a source table with a target and says what to do with matches and non-matches, in one statement. It's standard SQL, supported by SQL Server, Oracle and PostgreSQL 15 and later. A list of fee changes arrives: Git Basics goes up to $275.00, and a new course, Python Basics, starts at $450.00:

SQL▶ Try it
CREATE TABLE fee_updates (title VARCHAR(60), fee_usd NUMERIC(8,2));
INSERT INTO fee_updates VALUES ('Git Basics', 275.00), ('Python Basics', 450.00);
 
MERGE INTO courses AS c
USING fee_updates AS u
   ON c.title = u.title
WHEN MATCHED THEN
  UPDATE SET fee_usd = u.fee_usd
WHEN NOT MATCHED THEN
  INSERT (title, technology, level, fee_usd)
  VALUES (u.title, 'Python', 'Beginner', u.fee_usd)
RETURNING merge_action(), c.course_id, c.title, c.fee_usd;
Output
CREATE TABLE
 
INSERT 0 2
 
 merge_action | course_id |     title     | fee_usd
--------------+-----------+---------------+---------
 UPDATE       |         6 | Git Basics    |  275.00
 INSERT       |         7 | Python Basics |  450.00
(2 rows)

Git Basics matched an existing course, so it was updated; Python Basics didn't, so it was inserted as course 7. merge_action() reports which happened to each row (PostgreSQL 17 and later). MERGE can also DELETE matched rows, or add conditions, as in WHEN MATCHED AND u.fee_usd IS NULL THEN DELETE.

Git Basics matches and is updated to 275.00; Python Basics doesn't and is inserted as course 7

Upserts in Other Databases

DatabaseUpsert one rowMerge many
PostgreSQLINSERT ... ON CONFLICT (key) DO UPDATE SET ...MERGE (15+)
MySQLINSERT ... ON DUPLICATE KEY UPDATE col = VALUES(col)none
SQL ServerMERGEMERGE
OracleMERGEMERGE
SQLiteINSERT ... ON CONFLICT DO UPDATE (like PostgreSQL)none

Tabs showing each database's version are coming to this course.

ON CONFLICT, ON DUPLICATE KEY UPDATE and MERGE adding 30 minutes to Navika's total

Common Mistakes

Check-then-insert in two statements. Another session can insert between them. Use one upsert.

A conflict target without a unique constraint. ON CONFLICT (col) needs col to be unique or the primary key.

Overwriting instead of adding. SET minutes = EXCLUDED.minutes replaces the total; study_totals.minutes + EXCLUDED.minutes adds to it. Decide which you mean.

Updating columns that should stay. Leave original dates out of SET.

Interview Corner

What is an upsert, and how do you write one in PostgreSQL?

An insert that updates the existing row when the key already exists. In PostgreSQL: INSERT ... ON CONFLICT (key) DO UPDATE SET col = EXCLUDED.col, or DO NOTHING to skip.

What is EXCLUDED in ON CONFLICT?

A pseudo-table holding the row the INSERT tried to insert, so DO UPDATE can use the new values alongside the stored ones.

What's the difference between ON CONFLICT and MERGE?

ON CONFLICT handles conflicts for the rows of one INSERT, based on a unique constraint. MERGE joins a source to a target on any condition and can update, insert or delete per row; it's the SQL standard.

Practice

Challenge: Create study_totals (student_id INTEGER PRIMARY KEY, minutes INTEGER NOT NULL). Record three sessions in this order with upserts that add minutes: Navika (103) 45, Navika 30, Advitha (102) 60. Then show the table sorted by student_id.

Show solution
SQL▶ Try it
CREATE TABLE study_totals (
  student_id INTEGER PRIMARY KEY,
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_totals VALUES (103, 45), (102, 60)
ON CONFLICT (student_id) DO UPDATE SET minutes = study_totals.minutes + EXCLUDED.minutes;
 
INSERT INTO study_totals VALUES (103, 30)
ON CONFLICT (student_id) DO UPDATE SET minutes = study_totals.minutes + EXCLUDED.minutes;
 
SELECT * FROM study_totals ORDER BY student_id;
Output
CREATE TABLE
 
INSERT 0 2
 
INSERT 0 1
 
 student_id | minutes
------------+---------
        102 |      60
        103 |      75
(2 rows)

Advitha has 60, and Navika 75. One statement can carry several rows, but it can't touch the same row twice, which is why Navika's second session is its own statement.

Quick check: Upsert and MERGE

3 questions
1Navika's stored minutes are 45. What does INSERT ... VALUES (103, 30) ON CONFLICT (student_id) DO UPDATE SET minutes = study_totals.minutes + EXCLUDED.minutes leave?
2What is EXCLUDED.minutes?
3Which is the SQL-standard statement for "update matches, insert the rest"?

Key Takeaways

You want toWrite
Insert or add toON CONFLICT (student_id) DO UPDATE SET minutes = study_totals.minutes + EXCLUDED.minutes
Insert or replaceON CONFLICT (student_id) DO UPDATE SET minutes = EXCLUDED.minutes
Insert if missingON CONFLICT DO NOTHING
Sync from a listMERGE INTO courses c USING fee_updates u ON ... WHEN MATCHED ... WHEN NOT MATCHED ...

Was this tutorial helpful?

Lesson 58 of 115