MySQL INSERT, REPLACE, INSERT IGNORE and ON DUPLICATE KEY UPDATE

MySQL 60 min min read Updated: Nov 27, 2026 Beginner
MySQL INSERT, REPLACE, INSERT IGNORE and ON DUPLICATE KEY UPDATE
Beginner Topic 1 of 3

INSERT Basics

sql INSERT INTO customers (id, name, city, email, joined) VALUES (7, 'Gita Nair', 'Delhi', 'gita@example.com', '2025-02-01'); INSERT INTO customers (id, name, joined) VALUES (8, 'Hari Om', '2025-02-10'), (9, 'Isha Roy', '2025-02-11'); SELECT id, name, city FROM customers WHERE id >= 7 ORDER BY id;

Result:

idnamecity
7Gita NairDelhi
8Hari OmNULL
9Isha RoyNULL

The second statement inserted two rows at once. A multi-row insert is faster than many single inserts and is all-or-nothing in InnoDB.

AUTO_INCREMENT

Let MySQL create ids. A column marked AUTO_INCREMENT (it must be a key) gets the next number automatically.

sql CREATE TABLE notes (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, body VARCHAR(50) NOT NULL); INSERT INTO notes (body) VALUES ('first'), ('second'), ('third'); SELECT id, body FROM notes ORDER BY id;

Result:

idbody
1first
2second
3third

Ask for the id that was just created with LAST_INSERT_ID(). It is per connection, so other users cannot disturb it:

sql CREATE TABLE notes (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, body VARCHAR(50) NOT NULL); INSERT INTO notes (body) VALUES ('first'); INSERT INTO notes (body) VALUES ('second'); SELECT LAST_INSERT_ID() AS last_id;

Result:

last_id
2

After a multi-row insert, LAST_INSERT_ID() returns the id of the first row of that insert:

sql CREATE TABLE notes (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, body VARCHAR(50) NOT NULL); INSERT INTO notes (body) VALUES ('a'), ('b'), ('c'); SELECT LAST_INSERT_ID() AS first_id_of_batch, COUNT(*) AS rows_inserted FROM notes;

Result:

first_id_of_batchrows_inserted
13
Gaps are normal An id is used up even when the insert fails or a transaction rolls back. Never expect AUTO_INCREMENT ids to be continuous, and never use them to count rows.
sql CREATE TABLE notes (id INT AUTO_INCREMENT PRIMARY KEY, body VARCHAR(10) NOT NULL UNIQUE); INSERT INTO notes (body) VALUES ('a'); INSERT IGNORE INTO notes (body) VALUES ('a'); INSERT INTO notes (body) VALUES ('b'); SELECT id, body FROM notes ORDER BY id;

Result:

idbody
1a
3b

Notice that b got id 3, not 2: the ignored duplicate still consumed id 2.

When a Duplicate Appears: Four Choices

StatementOn duplicate key
INSERTError 1062, nothing inserted
INSERT IGNORESkips the bad row silently (with a warning)
REPLACE INTODeletes the old row, inserts the new one
INSERT ... ON DUPLICATE KEY UPDATEUpdates the existing row
sql INSERT INTO products (id, name, category, price, stock) VALUES (1, 'Laptop Pro', 'Electronics', 1099.00, 5);
Error

ERROR 1062: Duplicate entry '1' for key 'products.PRIMARY'

INSERT IGNORE

sql INSERT IGNORE INTO products (id, name, category, price, stock) VALUES (1, 'Laptop Pro', 'Electronics', 1099.00, 5), (9, 'Monitor', 'Electronics', 189.00, 20); SELECT id, name, price FROM products WHERE id IN (1, 9) ORDER BY id;

Result:

idnameprice
1Laptop899.00
9Monitor189.00

The duplicate row 1 was skipped, and the new row 9 was inserted. IGNORE also turns some other errors into warnings (for example truncated text), so use it carefully.

REPLACE INTO

REPLACE deletes the conflicting row and inserts the new one. That means columns you do not mention are reset to defaults, and foreign keys may block the delete:

sql CREATE TABLE settings (name VARCHAR(20) PRIMARY KEY, val VARCHAR(20), updated INT DEFAULT 0); INSERT INTO settings VALUES ('theme', 'light', 5); REPLACE INTO settings (name, val) VALUES ('theme', 'dark'); SELECT name, val, updated FROM settings;

Result:

namevalupdated
themedark0

updated went back to 0, because the old row was deleted. A parent row with child rows cannot be replaced:

sql REPLACE INTO customers (id, name, joined) VALUES (1, 'Asha R.', '2024-01-15');
Error

ERROR 1451: Cannot delete or update a parent row: a foreign key constraint fails ('shop'.'orders', CONSTRAINT 'orders_ibfk_1' FOREIGN KEY ('customer_id') REFERENCES 'customers' ('id'))

ON DUPLICATE KEY UPDATE: The Upsert

This updates only what you say and leaves everything else alone. It is the usual tool for "insert or update":

sql INSERT INTO products (id, name, category, price, stock) VALUES (1, 'Laptop', 'Electronics', 949.00, 12) ON DUPLICATE KEY UPDATE price = VALUES(price), stock = stock + 12; SELECT id, name, price, stock FROM products WHERE id = 1;

Result:

idnamepricestock
1Laptop949.0027

The old stock was 15, and stock + 12 made it 27. In MySQL 8.0.19 and later, a row alias is the newer style (VALUES(price) is deprecated):

sql INSERT INTO products (id, name, category, price, stock) VALUES (1, 'Laptop', 'Electronics', 949.00, 12) AS new_row ON DUPLICATE KEY UPDATE price = new_row.price, stock = products.stock + new_row.stock; SELECT id, name, price, stock FROM products WHERE id = 1;

Result:

idnamepricestock
1Laptop949.0027

A Counter with Upsert

sql CREATE TABLE page_views (page VARCHAR(30) PRIMARY KEY, views INT NOT NULL DEFAULT 0); INSERT INTO page_views (page, views) VALUES ('/home', 1) ON DUPLICATE KEY UPDATE views = views + 1; INSERT INTO page_views (page, views) VALUES ('/home', 1) ON DUPLICATE KEY UPDATE views = views + 1; INSERT INTO page_views (page, views) VALUES ('/about', 1) ON DUPLICATE KEY UPDATE views = views + 1; SELECT page, views FROM page_views ORDER BY page;

Result:

pageviews
/about1
/home2

It is safe even when many users hit the page at once, because the database does each increment atomically.

INSERT ... SELECT

sql CREATE TABLE city_stats (city VARCHAR(50) PRIMARY KEY, customers INT NOT NULL); INSERT INTO city_stats (city, customers) SELECT city, COUNT(*) FROM customers GROUP BY city; SELECT city, customers FROM city_stats ORDER BY city;

Result:

citycustomers
London2
Mumbai2
Singapore1
Tel Aviv1

How Many Rows Changed?

MySQL clients show "Query OK, 2 rows affected". Programs read the same number (ROW_COUNT()). With ON DUPLICATE KEY UPDATE, an existing row that was updated counts as 2, an inserted row counts as 1, and an unchanged row counts as 0:

sql CREATE TABLE t (id INT PRIMARY KEY, v INT); INSERT INTO t VALUES (1, 10); INSERT INTO t VALUES (1, 20) ON DUPLICATE KEY UPDATE v = VALUES(v); SELECT ROW_COUNT() AS updated_row_counts_as;

Result:

updated_row_counts_as
2

Common Beginner Mistakes

MistakeWhat happensFix
Using REPLACE as an updateDeletes and re-inserts, loses columns, fails with child rowsUse ON DUPLICATE KEY UPDATE
Using INSERT IGNORE to hide errorsBad data silently skippedHandle the error properly
Assuming ids have no gapsWrong countsUse COUNT(*)
Hand-picking idsClashes between usersUse AUTO_INCREMENT
LAST_INSERT_ID() after another insert on the same connectionGets the wrong idRead it right after the insert

Practice

  1. Create a visits table with AUTO_INCREMENT and insert 3 rows, then read the last id.
  2. Write an upsert that adds stock to a product, or creates it.
  3. Insert 3 rows with INSERT IGNORE where one is a duplicate.
  4. Copy all Electronics products into a new table with INSERT ... SELECT.

Conclusion

INSERT adds rows, AUTO_INCREMENT creates ids (with gaps), INSERT IGNORE skips duplicates, REPLACE deletes and re-inserts, and ON DUPLICATE KEY UPDATE is the clean upsert.

Quick Summary: INSERT, AUTO_INCREMENT, LAST_INSERT_ID, IGNORE, REPLACE, ON DUPLICATE KEY UPDATE, INSERT SELECT.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators