Skip to content
Learn Netverks

Lesson

Step 11/36 31% through track

on-duplicate-key

ON DUPLICATE KEY UPDATE

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches ON DUPLICATE KEY UPDATE: the SQL patterns, schema habits, and query reasoning you need before advancing in MySQL.

ID and upsert patterns differ from Postgres RETURNING—LAST_INSERT_ID and ON DUPLICATE KEY show up in PHP/Laravel codebases.

You will apply ON DUPLICATE KEY UPDATE in contexts like: Web apps on shared hosting, ecommerce, and many startups’ first production DB.

Copy MySQL SQL into the mysql client, local MySQL/MariaDB, or DB Fiddle (MySQL dialect)—use DESCRIBE and EXPLAIN where lessons show them. The in-browser lab ships later; mysql client is the practice path now.

When you can explain the previous lesson's ideas without copying example queries verbatim.

MySQL upsert: when INSERT hits a UNIQUE/PRIMARY conflict, update specified columns instead—common for counters and idempotent sync.

Upsert pattern

CREATE TABLE stats (
  metric VARCHAR(64) PRIMARY KEY,
  value BIGINT NOT NULL DEFAULT 0
);

INSERT INTO stats (metric, value) VALUES ('page_views', 1)
ON DUPLICATE KEY UPDATE value = value + 1;

Practice: Run on database practice in mysql client.

Requires unique key

Conflict detection uses PRIMARY or UNIQUE index—design keys intentionally.

Compare Postgres

Postgres uses ON CONFLICT … DO UPDATE—same idea, different syntax on PostgreSQL.

Important interview questions and answers

  1. Q: ON DUPLICATE KEY vs REPLACE?
    A: REPLACE deletes+inserts—triggers and FKs may suffer; upsert is gentler.
  2. Q: Affected rows count?
    A: Can be 1 or 2 on upsert—ORMs may interpret differently.

Self-check

  1. What index does upsert need?
  2. Increment counter on duplicate metric name.

Pitfall: Upsert without UNIQUE key silently inserts duplicates.

Interview prep

Requires?

PRIMARY or UNIQUE key conflict to trigger update clause.

Postgres equivalent?

ON CONFLICT DO UPDATE on PostgreSQL.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Upsert keys?
  • vs REPLACE?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump