MySQL INSERT & UPDATE: Full Guide from Basics to Error Fixes

目次

1. Introduction

MySQL is a popular relational database management system used in many web applications and database management systems. Among its features, the INSERT and UPDATE statements, which are used to add and modify data, play an essential role as basic data operations. Understanding them correctly and using them efficiently makes database management smoother. In this article, we will thoroughly explain everything from the basic usage of INSERT and UPDATE statements in MySQL to more advanced operations. The content is suitable for both beginners and intermediate users, so please use it as a reference.

2. Basics of INSERT Statements

Basic Syntax of INSERT Statements

The basic syntax of an INSERT statement is as follows.
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
For example, consider adding a new user to the users table.
INSERT INTO users (name, email, age)
VALUES ('Taro Yamada', 'taro@example.com', 30);
This SQL inserts the values ‘Taro Yamada’, ‘taro@example.com’, and 30 into the name, email, and age columns of the users table, respectively.

Inserting Multiple Rows

In MySQL, you can insert multiple rows of data at once. The syntax for that is as follows.
INSERT INTO users (name, email, age)
VALUES
('Hanako Sato', 'hanako@example.com', 25),
('Ichiro Suzuki', 'ichiro@example.com', 40);
Using this method reduces the number of database accesses and improves performance.

Handling NULL Values

When using INSERT statements, you may need to handle NULL values. For example, if age is not set, you would write:
INSERT INTO users (name, email, age)
VALUES ('Jiro Tanaka', 'jiro@example.com', NULL);
Note that if a column has a NOT NULL constraint, inserting a NULL value will cause an error. In that case, you must either set a default value or provide a value.

3. Basics of UPDATE Statements

Basic Syntax of UPDATE Statements

UPDATE statements are used to modify data in existing records. This section explains the basic syntax, how to updates, and the importance of the WHERE clause.
UPDATE table_name
SET column1 = new_value1, column2 = new_value2
WHERE condition;
For example, consider updating the age of a specific user in the users table.
UPDATE users
SET age = 35
WHERE name = 'Taro Yamada';
This SQL updates the age to 35 for the user whose name is ‘Taro Yamada’ in the users table.

Importance of the WHERE Clause

If you omit the WHERE clause in an UPDATE statement, all rows in the table will be updated. This can lead to unintended data loss, so always specify a condition.
-- When the WHERE clause is omitted
UPDATE users
SET age = 30;
This SQL sets the age to 30 for all users.

Conditional Updates

When specifying multiple conditions, use AND or OR.
UPDATE users
SET age = 28
WHERE name = 'Hanako Sato' AND email = 'hanako@example.com';
In this way, you can update data with more precise conditions.

4. Operations Combining INSERT and UPDATE

In database operations, adding new data and updating existing data can be mixed. In such scenarios, using INSERT ... ON DUPLICATE KEY UPDATE or REPLACE statements allows you to handle the process efficiently. This section explains each usage and its cautions in detail.

How to Use INSERT … ON DUPLICATE KEY UPDATE

INSERT ... ON DUPLICATE KEY UPDATE is effective when a primary key or unique key constraint exists. Using this syntax, you can update the data if it already exists or insert it if it does not, all in a single SQL statement.

Syntax

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON DUPLICATE KEY UPDATE
column1 = new_value1, column2 = new_value2, ...;

Example

Consider adding a new user to the users table. If the same email already exists, update that user’s name and age.
INSERT INTO users (email, name, age)
VALUES ('taro@example.com', 'Taro Yamada', 30)
ON DUPLICATE KEY UPDATE
name = VALUES(name),
age = VALUES(age);
This SQL statement performs the following actions:
  1. If a record with email = 'taro@example.com' does not exist, insert the data.
  2. If a record already exists, update the name and age.

Cautions

  • If there is an AUTO_INCREMENT column, the counter will increase even when a duplicate key occurs. This can cause unintended behavior, so be careful.
  • By using the VALUES() function, you can reuse the values you attempted to insert directly in the update.

How to Use REPLACE Statement and Differences

REPLACE statement completely deletes existing data when inserting new data. Unlike INSERT ... ON DUPLICATE KEY UPDATE, the original record is removed.

Syntax

REPLACE INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

Example

Insert data into the users table, and if the email is duplicated, delete the existing data and insert the new data.
REPLACE INTO users (email, name, age)
VALUES ('taro@example.com', 'Taro Yamada', 30);
This SQL statement performs the following actions:
  1. If a record with email = 'taro@example.com' exists, delete that record.
  2. Insert the new data.

Cautions

  • Because deletion and insertion occur, triggers and foreign key constraints may be affected.
  • Be aware of side effects from data deletion (loss of related data).

Performance Considerations

INSERT ... ON DUPLICATE KEY UPDATE and REPLACE statements each have advantages and disadvantages. In large databases or high-frequency operations, performance differences become important, so consider the following points.
CharacteristicINSERT … ON DUPLICATE KEY UPDATEREPLACE
Processing flowInsert or UpdateDelete + Insert
PerformanceGenerally fastSlightly slower due to delete and insert
Impact on foreign keys and triggersLittle impact, only updatesAffected during deletion
Data integrity riskLowRisk exists during deletion

Choosing Use Cases

  • Cases where INSERT … ON DUPLICATE KEY UPDATE is appropriate
  • When foreign key constraints or triggers exist and you want to avoid deletions.
  • When data is updated frequently.
  • Cases where REPLACE statement is appropriate
  • When a complete data replacement is needed.
  • For simple tables that are not affected by foreign key constraints or triggers.

5. Practical Example

Here we present real-world use cases that leverage MySQL’s INSERT and UPDATE statements, as well as “INSERT … ON DUPLICATE KEY UPDATE” and “REPLACE”. This helps you understand how to apply what you’ve learned in practice.

Use Case 1: Inventory Management System

In an inventory management system, product information is frequently added and stock levels are updated. Use INSERT to add new products, and UPDATE—or “INSERT … ON DUPLICATE KEY UPDATE”—to modify existing products.

Inserting and Updating Product Data

For example, suppose the product table products is defined as follows.
Column NameData TypeDescription
product_idINTProduct ID (primary key)
nameVARCHAR(255)Product Name
stockINTStock Quantity
Registering a New Product
INSERT INTO products (product_id, name, stock)
VALUES (1, 'Laptop', 50);
Updating Stock (Existing Product)
UPDATE products
SET stock = stock + 20
WHERE product_id = 1;
Insert or Update Stock
Use “INSERT … ON DUPLICATE KEY UPDATE” when you want to insert a new product or, if it already exists, update its stock.
INSERT INTO products (product_id, name, stock)
VALUES (1, 'Laptop', 50)
ON DUPLICATE KEY UPDATE
stock = stock + 50;
This SQL statement achieves the following:
  • If no record with product_id = 1 exists, insert it.
  • If a record with product_id = 1 exists, increase the stock by 50.

Use Case 2: User Information Management

In web applications, user information is routinely created and updated. Use INSERT for new users and UPDATE—or “INSERT … ON DUPLICATE KEY UPDATE”—for existing users.

User Table Structure

Column NameData TypeDescription
user_idINTUser ID (primary key)
nameVARCHAR(255)User Name
emailVARCHAR(255)Email Address
last_loginDATETIMELast Login Timestamp
Registering a New User
INSERT INTO users (user_id, name, email, last_login)
VALUES (1, 'Taro Yamada', 'taro@example.com', NOW());
Updating User Information
For example, when a user updates their profile.
UPDATE users
SET name = 'Hanako Yamada', email = 'hanako@example.com'
WHERE user_id = 1;
Insert or Update Information
When a user logs in for the first time, insert a new record; if the user already exists, update the last login timestamp.
INSERT INTO users (user_id, name, email, last_login)
VALUES (1, 'Taro Yamada', 'taro@example.com', NOW())
ON DUPLICATE KEY UPDATE
last_login = NOW();

Use Case 3: Periodic Data Updates

When dealing with sensor or log data, new records may be inserted every minute or second. In such cases, you need to either insert new data with INSERT or conditionally update existing data.

Inserting Log Data

Here is an example of a table sensor_logs that records sensor data.
Column NameData TypeDescription
sensor_idINTSensor ID (primary key)
temperatureFLOATTemperature
last_updatedDATETIMELast Updated Timestamp
Recording New Sensor Data
INSERT INTO sensor_logs (sensor_id, temperature, last_updated)
VALUES (1, 25.5, NOW());
Update or Insert Data
If the sensor_id already exists, update the data; otherwise, insert a new record.
INSERT INTO sensor_logs (sensor_id, temperature, last_updated)
VALUES (1, 25.5, NOW())
ON DUPLICATE KEY UPDATE
temperature = VALUES(temperature),
last_updated = VALUES(last_updated);

Cautions and Best Practices

  1. Error Handling: When using ON DUPLICATE KEY UPDATE or REPLACE, it’s important to verify the impact of triggers and foreign‑key constraints beforehand.
  2. Performance Optimization: For large datasets, design indexes and use transactions to perform operations efficiently.
  3. Data Integrity: Especially with REPLACE, which deletes and inserts rows, you need safeguards to prevent loss of related data.

6. Errors and Solutions

When using INSERT or UPDATE statements in MySQL, various errors can occur. This section explains common error examples, their causes, and specific solutions.

Common Error Examples

1. Duplicate Entry Error

Error Message:
Error: Duplicate entry '1' for key 'PRIMARY'
Cause:
  • Occurs when you try to insert a value that already exists into a column with a primary key or UNIQUE constraint.
Solution:
  • Use ON DUPLICATE KEY UPDATE: Performs an update when a duplicate entry exists.
INSERT INTO users (user_id, name, email)
VALUES (1, 'Taro Yamada', 'taro@example.com')
ON DUPLICATE KEY UPDATE
name = VALUES(name),
email = VALUES(email);
  • Check for existence before inserting data: Verify whether the data already exists to prevent duplicates.
SELECT COUNT(*) FROM users WHERE user_id = 1;

2. Foreign Key Constraint Error

Error Message:
Error: Cannot add or update a child row: a foreign key constraint fails
Cause:
  • Occurs when a foreign key constraint references a parent table record that does not exist.
Solution:
  • Insert the related data into the parent table.
INSERT INTO parent_table (id, name) VALUES (1, 'Parent Data');
  • Temporarily disable foreign key checks for the operation (not recommended).
SET FOREIGN_KEY_CHECKS = 0;
-- Data operation
SET FOREIGN_KEY_CHECKS = 1;

3. NULL Value Error

Error Message:
Error: Column 'name' cannot be null
Cause:
  • Occurs when you try to insert a NULL into a column that has a NOT NULL constraint.
Solution:
  • Set a default value.
ALTER TABLE users MODIFY name VARCHAR(255) 'Unset';
  • Insert appropriate values in the INSERT statement.
INSERT INTO users (name, email, age)
VALUES ('Taro Yamada', 'taro@example.com', NULL);

4. Data Type Error

Error Message:
Error: Data truncated for column 'age' at row 1
Cause:
  • Occurs when you try to insert or update a value that does not match the column’s data type.
Solution:
  • Check the data type and use an appropriate value.
INSERT INTO users (age) VALUES (30); -- For INT type
  • Change the column’s data type if needed.
ALTER TABLE users MODIFY age VARCHAR(10);

5. Table Lock Related Error

Error Message:
Error: Lock wait timeout exceeded; try restarting transaction
Cause:
  • Occurs when another transaction holds a lock on the table and it does not release within the wait timeout.
Solution:
  • To avoid transaction conflicts, perform the following actions.
  • Split queries to reduce table locking.
  • Create appropriate indexes to improve query execution speed.

Best Practices for Performance and Error Handling

  1. Leverage Transaction Management
  • When performing multiple INSERTs or UPDATEs at once, use transactions to manage the operations reliably.
START TRANSACTION;
INSERT INTO orders (order_id, user_id) VALUES (1, 1);
UPDATE users SET last_order = NOW() WHERE user_id = 1;
COMMIT;
  1. Optimize Indexes
  • Setting appropriate indexes on primary and foreign keys reduces error risk and improves performance.
ALTER TABLE users ADD INDEX (email);
  1. Rollback on Errors
  • If an error occurs, perform a rollback to maintain data integrity.
START TRANSACTION;
-- Some operations
ROLLBACK; -- On error

7. FAQ

When using MySQL INSERT or UPDATE statements, many people share common questions. This section deepens the reader’s understanding through frequently asked questions and their answers.

Q1: Which should I use, INSERT or UPDATE?

Answer:

Use INSERT to add new data, and UPDATE to modify existing data. However, when you need to both add new rows and update existing ones, using INSERT … ON DUPLICATE KEY UPDATE is the optimal solution. Example:
INSERT INTO users (user_id, name, email)
VALUES (1, 'Taro Yamada', 'taro@example.com')
ON DUPLICATE KEY UPDATE
name = VALUES(name),
email = VALUES(email);
This syntax allows you to add new rows and update existing ones in a single query.

Q2: Can ON DUPLICATE KEY UPDATE be used in all use cases?

Answer:

No, ON DUPLICATE KEY UPDATE has the following limitations.
  1. It works only when a primary key or unique key is defined. If none is set, no error occurs, but it won’t behave as intended.
  2. For large-scale data updates, performance may degrade. In such cases, consider using transactions or partitioning the data.

Q3: What is the difference between REPLACE and ON DUPLICATE KEY UPDATE?

Answer:

They are similar, but their behavior differs significantly.
FeatureON DUPLICATE KEY UPDATEREPLACE
Main operationUpdates data when a duplicate key existsDeletes and inserts new row when a duplicate key exists
Impact on foreign keys and triggersOnly updates, minimal impactMay affect them during deletion
PerformanceGenerally fastSlightly slower because it deletes and inserts
Data integrity riskLowRisk exists during deletion
As a rule of thumb, use ON DUPLICATE KEY UPDATE when you want to update without deleting, and use REPLACE when you need to completely replace the row.

Q4: What happens if I forget the WHERE clause?

Answer:

If you run an UPDATE without a WHERE clause, all rows in the table are updated. This is extremely dangerous and can cause unintended data changes. Example:
-- Updates the age of all records to 30
UPDATE users
SET age = 30;
Mitigation:
  • Always specify a WHERE clause to update only the rows that meet specific conditions.
  • As a best practice, run a SELECT statement first to verify the target data before executing the UPDATE.
SELECT * FROM users WHERE name = 'Taro Yamada';
UPDATE users SET age = 35 WHERE name = 'Taro Yamada';

Q5: Are there ways to speed up INSERT and UPDATE statements?

Answer:

You can improve performance using the following methods.
  1. Optimize indexes: Setting appropriate indexes on necessary columns speeds up searches and updates.
CREATE INDEX idx_email ON users(email);
  1. Batch operations: Inserting or updating multiple rows at once is more efficient than processing them one by one.
INSERT INTO users (name, email, age)
VALUES
('Hanako Sato', 'hanako@example.com', 25),
('Ichiro Suzuki', 'ichiro@example.com', 40);
  1. Use transactions: Wrapping multiple operations in a single transaction reduces lock contention.
START TRANSACTION;
INSERT INTO orders (order_id, user_id) VALUES (1, 1);
UPDATE users SET last_order = NOW() WHERE user_id = 1;
COMMIT;
  1. Avoid unnecessary operations: Verify data beforehand to prevent needless updates or inserts.
SELECT COUNT(*) FROM users WHERE user_id = 1;
-- Avoid unnecessary inserts or updates

Q6: How can I prevent errors with INSERT or UPDATE?

Answer:

To prevent errors, use the following practices.
  • Check data types: Ensure the data being inserted or updated matches the column’s data type.
  • Set constraints properly: Correctly define primary keys, unique keys, and foreign key constraints to maintain data integrity.
  • Error handling: Implement appropriate error handling in your application.
-- Roll back on error
START TRANSACTION;
INSERT INTO users (user_id, name, email) VALUES (1, 'Taro Yamada', 'taro@example.com');
ROLLBACK; -- As needed

8. Summary

In this article, we covered everything from the basics of INSERT and UPDATE statements in MySQL to advanced operations, practical use cases, error handling, and answers to common questions. Below, let’s review the key points.

Key Points of This Article

1. Basics of INSERT Statements

  • INSERT statements are used to add new data to a table.
  • They can insert multiple rows at once, enabling efficient operations.
  • Be mindful of NULL values and NOT NULL constraints.

2. Basics of UPDATE Statements

  • UPDATE statements are used to modify existing data based on conditions.
  • Always specify a WHERE clause to avoid unintentionally updating all rows.

3. Combining INSERT and UPDATE

  • INSERT ... ON DUPLICATE KEY UPDATE inserts new data or updates existing rows in a single operation.
  • The REPLACE statement deletes and re-inserts data, so be aware of its impact on triggers and foreign keys.

4. Practical Examples

  • We learned how to use INSERT and UPDATE statements in use cases such as inventory management and user information management.
  • We presented best practices for handling multiple operations efficiently.

5. Errors and Mitigations

  • We explained the causes and solutions for common issues such as duplicate entries, foreign key violations, and NULL insertion errors.
  • Leveraging transactions and proper index design is essential.

6. FAQ

  • We answered common questions about when to use INSERT vs. UPDATE, the scope of ON DUPLICATE KEY UPDATE, and performance optimization techniques.

Next Steps

INSERT and UPDATE statements in MySQL are fundamental database operations and essential skills for any application development. Based on what you learned in this article, consider the following next steps.
  1. Learn Transaction Management: Deepen your understanding of how to use transactions for more advanced database operations.
  2. Optimize Index Design: Learn how to design indexes that maintain query performance as data volume grows.
  3. Log Management for Errors: Implement logging and analysis methods to quickly pinpoint causes when errors occur.
  4. Leverage the Official MySQL Documentation: For more detailed information and the latest features, refer to the official MySQL documentation.

Conclusion

We hope this article serves as a helpful reference for understanding and using INSERT and UPDATE statements efficiently. Mastering basic data manipulation will improve your database management skills and enable you to tackle more advanced application development. Keep deepening your MySQL knowledge!