INSERT — Adding New Records
Add single rows, multiple rows, and even copy data from one table into another with INSERT.
INSERT puts new rows into a table. You control exactly which columns get data and what those values are.
EXERCISE
1INSERT — Adding New Rows
INSERT puts new rows into a table. You specify which columns get values and what those values are — and MySQL handles the rest, including auto-generated IDs.
Basic INSERT syntax:
-- Single row — specify columns (recommended):
INSERT INTO customers (name, email, city)
VALUES ('Arjun Mehta', 'arjun@example.com', 'Mumbai');
-- Single row — without column list (positional, fragile):
INSERT INTO customers
VALUES (NULL, 'Arjun Mehta', 'arjun@example.com', 'Mumbai');
-- Every column must be accounted for including the auto-increment id (NULL = auto)
Multiple rows in one INSERT:
INSERT INTO products (name, price, category, stock_qty)
VALUES
('Wireless Mouse', 599.00, 'Electronics', 150),
('USB-C Hub', 1299.00, 'Electronics', 75),
('Desk Lamp', 449.00, 'Home Office', 200),
('Notebook A5', 99.00, 'Stationery', 500);
-- One statement, four rows — faster than four separate INSERTs
INSERT ... SELECT — copying data between tables:
-- Archive completed orders older than 1 year:
INSERT INTO orders_archive (id, customer_id, total, order_date, status)
SELECT id, customer_id, total, order_date, status
FROM orders
WHERE status = 'completed'
AND order_date < DATE_SUB(CURDATE(), INTERVAL 1 YEAR);
INSERT IGNORE — skip rows that would cause a duplicate key error:
INSERT IGNORE INTO subscribers (email)
VALUES ('priya@example.com');
-- If email already exists (UNIQUE constraint), silently skips — no error
Pro Tip: Always specify column names in INSERT. If someone later adds a column to the table, positional INSERTs without column names will start inserting values into the wrong columns.
EXERCISE
2INSERT ON DUPLICATE KEY UPDATE (Upsert)
Sometimes you want to insert a row if it does not exist, or update it if it does. MySQL handles this elegantly with ON DUPLICATE KEY UPDATE — called an "upsert".
The problem — insert or update?
-- You want to record a page view count.
-- If the page has no row yet: INSERT.
-- If the page already has a row: UPDATE the count.
-- Doing this with two queries (SELECT then INSERT or UPDATE) has race conditions.
ON DUPLICATE KEY UPDATE:
-- Insert product, or update price if SKU already exists:
INSERT INTO products (sku, name, price)
VALUES ('SKU-001', 'Wireless Mouse', 599.00)
ON DUPLICATE KEY UPDATE
price = VALUES(price), -- use the value from the INSERT attempt
updated_at = NOW();
-- The SKU column must have a UNIQUE or PRIMARY KEY constraint
Tracking counts with upsert:
-- Page view counter:
INSERT INTO page_views (page_url, view_count)
VALUES ('/products/wireless-mouse', 1)
ON DUPLICATE KEY UPDATE
view_count = view_count + 1, -- increment existing count
last_viewed = NOW();
REPLACE INTO (alternative — use carefully):
-- REPLACE deletes the old row and inserts a new one:
REPLACE INTO products (sku, name, price)
VALUES ('SKU-001', 'Wireless Mouse', 649.00);
-- WARNING: This triggers DELETE + INSERT, not UPDATE.
-- AUTO_INCREMENT id changes. Foreign keys can break.
-- Prefer ON DUPLICATE KEY UPDATE in most cases.
Pro Tip: ON DUPLICATE KEY UPDATE is one of the most useful MySQL features for production systems. It is atomic (safe for concurrent users), efficient, and avoids the race condition of a SELECT-then-INSERT approach.
EXERCISE
3AUTO_INCREMENT Behaviour After INSERT
After every INSERT, MySQL tracks the last generated ID — and you can retrieve it immediately to use in related inserts.
Retrieving the last inserted ID:
-- Insert a new customer:
INSERT INTO customers (name, email)
VALUES ('Priya', 'priya@example.com');
-- Get the auto-generated id immediately after:
SELECT LAST_INSERT_ID();
-- Output: 42 (whatever id was just assigned)
Using LAST_INSERT_ID() to chain related inserts:
-- Step 1: Insert a new customer:
INSERT INTO customers (name, email)
VALUES ('Rohan', 'rohan@example.com');
-- Step 2: Immediately create their first order using the new id:
INSERT INTO orders (customer_id, total, status)
VALUES (LAST_INSERT_ID(), 1499.00, 'pending');
-- The foreign key is correct without ever knowing the id manually
AUTO_INCREMENT does NOT reuse deleted IDs:
-- customers: id 1, 2, 3
DELETE FROM customers WHERE id = 3;
-- customers: id 1, 2
INSERT INTO customers (name) VALUES ('New Person');
-- New id will be 4, NOT 3
-- Gaps in AUTO_INCREMENT are normal and expected
Checking the next AUTO_INCREMENT value:
-- See current AUTO_INCREMENT counter for a table:
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'customers';
Resetting AUTO_INCREMENT (only when table is empty):
ALTER TABLE customers AUTO_INCREMENT = 1;
-- Only do this when rebuilding a test database or after TRUNCATE
Pro Tip:
LAST_INSERT_ID()is session-specific — it returns the ID from YOUR last insert, not anyone else's. This makes it safe to use in multi-user applications without race conditions.
