MySQL: A Detailed Explanation of MySQL Insert, Delete, and…

Last updated: 2026-08-26

Inserting, updating, and deleting data are basic database operations—INSERT, UPDATE, and DELETE are the core of DML.

This lesson provides a systematic explanation of how to insert, update, and delete data.

100%
graph TB
    A[DML Operation] --> B[INSERT Insert]
    A --> C[UPDATE Update]
    A --> D[DELETE Delete]
    B --> B1[Single-row insertion]
    B --> B2[Multi-line Insertion]
    B --> B3[Subquery Insertion]
    B --> B4[UPSERT]
    C --> C1[Conditional Update]
    C --> C2[JOIN Update]
    D --> D1[Conditional Deletion]
    D --> D2[TRUNCATE Clear]

1. What You'll Learn



2. A True Story

(1) Pain Point: Manually entering data one by one is extremely inefficient

The inventory management system processes over 10,000 data writes daily. Operations staff manually perform INSERT and UPDATE operations one by one, which is not only extremely inefficient but also frequently leads to data corruption due to copy-and-paste errors. During a batch price adjustment, executing UPDATE statements one by one took three hours; during that time, a staff member accidentally entered the wrong WHERE clause, causing all prices in the entire table to be set to 0.

(2) A Solution Combining Batch Operations and Transactions

Use batch INSERTs, transactional UPDATEs, and conditional DELETEs, combined with INSERT ON DUPLICATE KEY UPDATE, to process all data in a single operation.

Dimension Individual Operations Batch Operations + Transactions
10,000 writes ~3 hours ~3 minutes
Risk of Error High (prone to manual errors) Low (transaction protection)
Network Round Trips 10,000 1
Speed Increase 50x


3. INSERT: Inserting Data

▶ Example: Single-line insertion

SQL
-- Insert in Full
INSERT INTO users (username, email, age) 
VALUES ('alice', 'alice@email.com', 25);

-- Omit field names(Must be in order)
INSERT INTO users VALUES (1, 'bob', 'bob@email.com', 30);
▶ Try it Yourself

Output:

TEXT 📖 Display only
Query OK, 1 row affected

▶ Example: Inserting Multiple Lines

SQL
INSERT INTO products (name, price, category) VALUES
('iPhone', 999, 'Phone'),
('MacBook', 1999, 'Laptop'),
('iPad', 599, 'Tablet');
▶ Try it Yourself

Output:

TEXT 📖 Display only
Query OK, 1 row affected

▶ Example: Inserting a subquery

SQL
-- Insert from Query Results
INSERT INTO user_archive (id, name, email)
SELECT id, name, email FROM users WHERE status = 'deleted';
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed


4. UPDATE: Update Data

▶ Example: Conditional Update

SQL
-- Update a Single Record
UPDATE users SET email = 'new@email.com' WHERE id = 1;

-- Update Multiple Records
UPDATE products SET price = price * 1.1 WHERE category = 'Electronics';

-- Multi-Field Update
UPDATE users SET age = age + 1, status = 'active' WHERE id = 1;
▶ Try it Yourself

Output:

TEXT 📖 Display only
Query OK, 1 row affected
Rows matched: 1  Changed: 1  Warnings: 0

▶ Example: UPDATE + JOIN

SQL
-- Related Updates
UPDATE orders o
INNER JOIN customers c ON o.customer_id = c.id
SET o.status = 'priority'
WHERE c.level = 'VIP';
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed


5. DELETE: Deleting Data

▶ Example: Conditional Deletion

SQL
-- Delete a Single Record
DELETE FROM users WHERE id = 1;

-- Delete Multiple Records
DELETE FROM orders WHERE status = 'cancelled' AND created_at < '2025-01-01';

-- Deleting Related Records
DELETE o FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE c.status = 'banned';
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed

(1) TRUNCATE vs DELETE

Dimension TRUNCATE DELETE
Speed Very fast Slow
Transaction Non-rollback Rollback
Trigger Not triggered Triggered
AUTO_INCREMENT Reset Do not reset
WHERE Not supported Supported
SQL
-- Clear the table (Non-rollbackable)
TRUNCATE TABLE temp_data;


6. INSERT ON DUPLICATE KEY UPDATE

Execute the update if there is a primary key or unique key conflict.


7. REPLACE INTO

Delete first, then insert (in case of a conflict).


8. Safety Guidelines

Action Recommendation
UPDATE/DELETE Must include a WHERE clause; first use SELECT to confirm the scope of the operation
Bulk Operations Execute in batches of 1,000–5,000 rows each
Production Environment Start a transaction, then COMMIT after confirmation
Backup Before the operation mysqldump Backup

❓ FAQ

Q Does the field order in an INSERT statement have to match the table definition?
A It only needs to match when field names are omitted. It is recommended to explicitly specify field names so as not to rely on order.
Q Can data be recovered after a DELETE?
A You can ROLLBACK within a transaction. For data that has been COMMITTED, you'll need to restore it from a backup. A TRUNCATE cannot be rolled back.
Q How can I optimize bulk INSERT operations?
A Use multi-row VALUES, turn off auto-commit, disable indexes, and use LOAD DATA INFILE.
Q What is the difference between INSERT and REPLACE?
A INSERT returns an error if it encounters a unique key conflict, while REPLACE deletes the record before inserting a new one (the ID will change). We recommend using ON DUPLICATE KEY UPDATE.
Q What is the difference between DELETE and TRUNCATE?
A DELETE deletes rows one by one and is rollback-capable, while TRUNCATE empties the table, is not rollback-capable, but is extremely fast.

📖 Summary


📝 Exercises

  1. Basic Problem (Difficulty ⭐): Insert 5 test records into the users table.

  2. Advanced Problem (Difficulty: ⭐⭐): Implement a visit counter using INSERT ON DUPLICATE KEY UPDATE.

  3. Challenge (Difficulty: ⭐⭐⭐): Write a script to securely delete temporary data from 30 days ago, using transaction protection.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏