iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

INSERT

INSERT in MySQL covers single rows, bulk INSERTs, INSERT…SELECT, and the upsert family (ON DUPLICATE KEY UPDATE / INSERT IGNORE).

Every flavour

EXAMPLE
-- Single row
INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada');
SELECT LAST_INSERT_ID();

-- Multiple rows — much faster than N round trips
INSERT INTO users (email, name) VALUES
    ('ada@example.com', 'Ada'),
    ('bo@example.com',  'Bo'),
    ('cy@example.com',  'Cy');

-- INSERT ... SELECT — copy / transform from another table
INSERT INTO posts_archive (id, title, body, archived_at)
SELECT id, title, body, NOW()
FROM   posts
WHERE  created_at < NOW() - INTERVAL 1 YEAR;

-- ON DUPLICATE KEY UPDATE — upsert via UNIQUE / PRIMARY conflict
INSERT INTO users (email, name, login_count)
VALUES ('ada@example.com', 'Ada Lovelace', 1)
ON DUPLICATE KEY UPDATE
    name        = VALUES(name),
    login_count = login_count + 1;

-- INSERT IGNORE — silently skip duplicate-key errors
INSERT IGNORE INTO unique_tags (tag) VALUES ('mysql');

-- REPLACE — DELETE + INSERT (resets auto-incremented id! use sparingly)
REPLACE INTO settings (key, value) VALUES ('theme', 'dark');

-- Tip: enable strict mode to surface silent truncation
SET sql_mode = 'STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY';

Why it matters

VALUES(col) inside ON DUPLICATE KEY UPDATE is deprecated in MySQL 8.0.20+. The replacement: INSERT … AS new ON DUPLICATE KEY UPDATE col = new.col.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada');
SELECT LAST_INSERT_ID();
Try it Yourself »

Discussion

Loading…