SQL / MySQL Intermediate Queries · 8 min read

INSERT ... ON DUPLICATE KEY UPDATE

Lesson 21 of 33 in the SQL / MySQL learning path.

How do I insert a row or update it when the unique key exists?

An enrollment should exist once for a student in a lesson. A plain INSERT fails when that pair is already there, and a plain UPDATE does nothing when it is missing. INSERT with ON DUPLICATE KEY UPDATE does both jobs. MySQL inserts the row when no unique key collides, and it updates the existing row when one does.

The unique key in this lesson is (lesson_id, user_id). The first statement stores Ada as waitlist. The second statement confirms Ada and inserts Grace. On MySQL 8.0.19 and newer, the row alias after VALUES names the values you just sent, and the UPDATE clause copies the new status from that alias.

Syntax & Parameters

Syntax
INSERT INTO enrollments (lesson_id, user_id, status)
VALUES (1, 1, 'confirmed') AS new_row
ON DUPLICATE KEY UPDATE status = new_row.status;

Example

queries.sql
CREATE DATABASE IF NOT EXISTS school
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE school;

SET NAMES utf8mb4;

DROP VIEW IF EXISTS roster;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS lessons;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(254) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE lessons (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  title VARCHAR(160) NOT NULL,
  track VARCHAR(80) NOT NULL,
  published_at DATETIME NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE enrollments (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  lesson_id INT UNSIGNED NOT NULL,
  user_id INT UNSIGNED NOT NULL,
  status VARCHAR(20) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_enrollments_lesson_user (lesson_id, user_id),
  CONSTRAINT fk_enrollments_lesson FOREIGN KEY (lesson_id) REFERENCES lessons (id),
  CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (name, email, created_at) VALUES
  ('Ada Lovelace', 'ada@school.test', '2026-03-01 09:00:00'),
  ('Grace Hopper', 'grace@school.test', '2026-03-14 11:00:00');

INSERT INTO lessons (title, track, published_at) VALUES
  ('Algebra I', 'math', '2026-03-02 09:00:00');

INSERT INTO enrollments (lesson_id, user_id, status) VALUES
  (1, 1, 'waitlist');

SELECT id, lesson_id, user_id, status
FROM enrollments
ORDER BY id;

INSERT INTO enrollments (lesson_id, user_id, status)
VALUES
  (1, 1, 'confirmed'),
  (1, 2, 'confirmed') AS new_row
ON DUPLICATE KEY UPDATE
  status = new_row.status;

SELECT id, lesson_id, user_id, status
FROM enrollments
ORDER BY id;

Expected Output

id | lesson_id | user_id | status
1  | 1         | 1       | waitlist
1 row in set

Query OK, 3 rows affected
Records: 2  Duplicates: 1  Warnings: 0

id | lesson_id | user_id | status
1  | 1         | 1       | confirmed
2  | 1         | 2       | confirmed
2 rows in set

Line-by-Line Walkthrough

  1. users and lessons are created first because enrollments has foreign keys to both.
  2. UNIQUE KEY uq_enrollments_lesson_user on (lesson_id, user_id) is the key that makes one seat per student per lesson.
  3. The ordinary INSERT stores Ada in Algebra I with status waitlist. The following SELECT shows that single row.
  4. The next INSERT lists Ada again as confirmed and Grace as confirmed. AS new_row names those incoming values. This alias form needs MySQL 8.0.19 or newer.
  5. Ada collides with the unique key, so MySQL keeps id 1 and sets status from new_row.status, which changes waitlist to confirmed.
  6. Grace does not collide, so MySQL inserts a new row with the next id and status confirmed.
  7. A changed duplicate counts as two affected rows and a fresh insert counts as one. This statement reports 3 rows affected, with 2 records and 1 duplicate.
  8. The last SELECT shows Ada confirmed on the original id and Grace confirmed on a new id. There are still two rows, not three.
  9. From PHP, send lesson_id, user_id, and status as bound parameters on this same statement shape. The unique key has to exist in the table or the statement always inserts.

Common Pitfalls & Security

ON DUPLICATE KEY UPDATE fires for every unique key and primary key the new row hits, not only the key you had in mind. Without the composite unique key, the same student can be enrolled twice and the UPDATE arm never runs.

  • A second unique column, such as a unique email on a users upsert, can update the wrong person when that other key collides.
  • The client count is easy to misread. An insert reports 1, a real change reports 2, and a statement that writes the same status again can report 0 for that row.
  • AUTO_INCREMENT still advances when the statement takes the update path, so ids can gain gaps.
  • A foreign key is checked too. lesson_id or user_id that does not exist fails the statement before the duplicate rule matters.
  • This is one statement, not a lock around a second table. A payment row that must appear with the enrollment still belongs in a transaction.

Best Practices & Modern Standards

Put a unique key on the real identity of the row, here lesson_id plus user_id, and update only the columns that should change, here status. Use the row alias form, new_row.status, on current MySQL 8. Keep the INSERT column list explicit so a new column with a default does not get overwritten by accident.

From application code, bind every value and check the affected-row count only if the caller must tell an insert from an update. When two writers can upsert the same seat, the unique key is what keeps a single row. Add a transaction when the enrollment change must commit together with another table.

Real-World Use

Ada clicks Confirm after she was already on the Algebra I waitlist, and Grace confirms for the first time in the same import file. One INSERT with ON DUPLICATE KEY UPDATE confirms Ada in place and inserts Grace. The office does not have to look up the row first, and the unique key stops a double enrollment.

Frequently Asked Questions

Which key makes MySQL update instead of insert?

Any primary key or unique key the new row duplicates. In this table that is uq_enrollments_lesson_user on lesson_id and user_id.

Why does the client report 3 rows affected for 2 records?

MySQL counts a fresh insert as 1 and a duplicate that actually changes as 2. Grace adds 1 and Ada adds 2, which is 3, with Records: 2 and Duplicates: 1.

What happens if I forget the unique key?

Every execution inserts another row. ON DUPLICATE KEY UPDATE has nothing to collide with, so Ada can end up enrolled twice.

Should I use VALUES(status) in the UPDATE clause?

Use the row alias. VALUES() inside ON DUPLICATE KEY UPDATE is deprecated as of MySQL 8.0.20. new_row.status is the form this lesson uses, and it requires MySQL 8.0.19 or newer.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…