MySQL INSERT vs UPDATE: Syntax, Examples, and Best Practices (With ON DUPLICATE KEY UPDATE)

目次

1. Introduction

MySQL is one of the most widely used database management systems. Among its core operations, INSERT and UPDATE are fundamental SQL statements frequently used to add and modify data in a database. They play a critical role in everyday tasks such as managing product information for e-commerce sites and registering or updating user data.

Understanding these basic operations correctly and using them efficiently is essential for effective database administration. This article is designed for beginners to intermediate users and explains everything from the fundamentals of INSERT and UPDATE to practical real-world applications. We also cover key precautions and best practices to help you manage data more safely and effectively.

In the next section, we’ll explain the basic syntax of the INSERT statement and how to use it. This content is intended to be helpful whether you’re reviewing SQL basics or learning something new.

2. INSERT Statement: Basic Syntax and Usage

The INSERT statement is used to add new data to a database. While it is one of the most basic SQL statements in MySQL, it plays a crucial role in supporting the foundation of data management. In this section, we explain the basic syntax, practical examples, and important points to keep in mind when using INSERT.

Basic INSERT Syntax

The basic syntax of an INSERT statement is as follows.

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
  • table_name: The name of the table to insert data into.
  • column1, column2, …: The column names that correspond to the values being inserted.
  • value1, value2, …: The actual data values to insert.

Example

For example, if you want to add a new user’s name and email address to the users table, you can use the following SQL statement.

INSERT INTO users (name, email)
VALUES ('Taro Yamada', 'taro@example.com');

This statement inserts 'Taro Yamada' into the name column and 'taro@example.com' into the email column of the users table.

INSERT Options

1. Insert Multiple Rows at Once

You can also insert multiple rows in a single INSERT statement. In the example below, two users are added to the users table at the same time.

INSERT INTO users (name, email)
VALUES 
  ('Hanako Yamada', 'hanako@example.com'),
  ('Jiro Sato', 'jiro@example.com');

This method is efficient when inserting multiple rows.

2. Insert Data into Specific Columns Only

You don’t have to insert data into every column. You can insert data into only specific columns as needed.

INSERT INTO users (name)
VALUES ('Ichiro Suzuki');

In this case, the email column will be set to NULL or its default value (if configured).

Important Notes When Using INSERT

  1. Match Columns and Values Correctly
  • The number and order of columns specified must match the number and order of values in the VALUES clause.
  • Example:
    sql INSERT INTO users (name, email) VALUES ('Yoko Ota', 'yoko@example.com'); -- Correct
  1. Check Unique Key Constraints
  • You should verify in advance that the data being inserted does not duplicate existing data.
  • Inserting duplicate data that violates a unique constraint will result in an error.
  1. Use Default Values When Appropriate
  • If you omit a value for a specific column, MySQL will insert the default value defined in the table schema (if available).

3. UPDATE Statement: Basic Syntax and Usage

The UPDATE statement is used to modify existing data. For example, it can be used to change user information or update inventory counts. In this section, we cover the basic syntax, practical examples, and key precautions when using UPDATE.

Basic UPDATE Syntax

The basic syntax of an UPDATE statement is as follows.

UPDATE table_name
SET column1 = new_value1, column2 = new_value2, ...
WHERE condition;
  • table_name: The table to update.
  • SET clause: The columns to update and their new values.
  • WHERE clause: The condition that determines which rows are updated. If omitted, all rows in the table will be updated.

Example

Below is an example that updates the email address for a specific user in the users table.

UPDATE users
SET email = 'newemail@example.com'
WHERE id = 1;

This statement updates the email address to newemail@example.com for the user whose id is 1.

Important Notes When Using UPDATE

1. Why the WHERE Clause Matters

If you omit the WHERE clause, every row in the table will be updated. In the example below, the email column would be changed to the same value for all rows—so be careful.

UPDATE users
SET email = 'sameemail@example.com'; -- Updates all rows

To avoid accidentally modifying all data, always specify the required condition.

2. Updating Multiple Columns

To update multiple columns at once, list them in the SET clause separated by commas.

UPDATE users
SET name = 'Jiro Yamada', email = 'jiro@example.com'
WHERE id = 2;

This statement updates both the name and email address for the user with id 2.

3. Table Locks and Performance

  • When you run an UPDATE statement, MySQL may lock the target table or rows. Updating large amounts of data can impact performance.
  • When needed, consider batch processing and proper index usage to improve performance.

Practical Examples

Update a User’s Active Status

The example below updates the status to active for users who meet a specific condition.

UPDATE users
SET status = 'active'
WHERE last_login > '2025-01-01';

This statement sets users to active if their last login time is after January 1, 2025.

Decrease Inventory Stock

To reduce a product’s stock based on its current value, you can calculate directly in the SET clause.

UPDATE products
SET stock = stock - 1
WHERE product_id = 101;

This statement decreases the stock by 1 for the product with product_id 101.

Advanced UPDATE Usage

You can also update values using data from other tables. For example, here’s a pattern that updates by referencing another table.

UPDATE users u
JOIN orders o ON u.id = o.user_id
SET u.last_order_date = o.order_date
WHERE o.order_status = 'completed';

This statement applies the completed order date from the orders table to the users table’s last_order_date column.

Summary

The UPDATE statement is essential for modifying data. By understanding the basic syntax and using the WHERE clause appropriately, you can update data safely and efficiently. In the next section, we’ll explain how to combine INSERT and UPDATE to perform even more efficient operations.

4. How to Combine INSERT and UPDATE

In MySQL, you can combine INSERT and UPDATE to manage data efficiently. This allows you to perform an operation that inserts a new row if it does not exist, or updates it if it already exists—within a single SQL statement. In this section, we focus on how to use ON DUPLICATE KEY UPDATE.

What Is ON DUPLICATE KEY UPDATE?

ON DUPLICATE KEY UPDATE is a convenient feature that unifies the behavior of INSERT and UPDATE. By using this syntax, you can make inserts and updates more efficient.

The basic syntax is as follows.

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON DUPLICATE KEY UPDATE
column1 = new_value1, column2 = new_value2, ...;
  • INSERT part: Adds new data.
  • ON DUPLICATE KEY UPDATE part: Updates data if a unique key conflict is detected during insert.

Examples

Basic Example

The following example inserts data into the users table and updates an existing user name if a duplicate key is found.

INSERT INTO users (id, name, email)
VALUES (1, 'Taro Yamada', 'taro@example.com')
ON DUPLICATE KEY UPDATE
name = 'Taro Yamada', email = 'taro@example.com';

This statement performs the following actions:

  1. If no row exists with id = 1, it inserts a new record.
  2. If a row already exists with id = 1, it updates name and email.

Inventory Management Example

This syntax is also useful for updating or inserting product stock counts.

INSERT INTO inventory (product_id, stock)
VALUES (101, 50)
ON DUPLICATE KEY UPDATE
stock = stock + 50;

This statement does the following:

  1. If there is no product with product_id = 101, it inserts a new record.
  2. If it already exists, it adds 50 to the stock count (stock).

Key Points to Watch

1. A Unique Key Is Required

ON DUPLICATE KEY UPDATE works only when a unique key (PRIMARY KEY or UNIQUE index) is defined on the table. If there is no unique key, it will fail with an error.

2. AUTO_INCREMENT Still Increases

When you use ON DUPLICATE KEY UPDATE, the AUTO_INCREMENT value can increase even if a duplicate key is detected. This is because MySQL advances the counter once it attempts the insert.

INSERT INTO users (id, name)
VALUES (NULL, 'Hanako Suzuki')
ON DUPLICATE KEY UPDATE
name = 'Hanako Suzuki';

In this case, the AUTO_INCREMENT value increases even when a duplicate occurs.

3. Performance Impact

When handling large volumes of data, ON DUPLICATE KEY UPDATE can impact performance. If frequent insert/update operations are needed, consider using transactions to improve efficiency.

Advanced Example

Consolidating Data Across Tables

You can also use ON DUPLICATE KEY UPDATE while inserting data from another table.

INSERT INTO users (id, name, email)
SELECT id, full_name, dept
FROM external_users
ON DUPLICATE KEY UPDATE
name = VALUES(name),
department = VALUES(department);

This statement inserts data from the external_users table into the users table, and updates existing rows when duplicates are found.

Summary

ON DUPLICATE KEY UPDATE is a powerful tool for efficient data management in MySQL. By using it, you can perform inserts and updates in a single SQL statement, improving code simplicity and potentially boosting performance. In the next section, we’ll introduce more detailed real-world scenarios where this pattern is especially useful.

5. Practical Examples: Learn Through Real-World Scenarios

Here, we’ll show how to use INSERT ... ON DUPLICATE KEY UPDATE and basic INSERT/UPDATE statements in real-world scenarios. By studying these examples, you can build practical skills that transfer directly to production work.

Scenario 1: Managing Product Inventory for an E-Commerce Site

In e-commerce, new products may be added, and existing products may be restocked. In these cases, you need an efficient way to manage inventory counts.

Example

The following SQL statement inserts a new product or updates the stock count for an existing product.

INSERT INTO inventory (product_id, product_name, stock)
VALUES (101, 'Laptop', 50)
ON DUPLICATE KEY UPDATE
stock = stock + 50;
  • Explanation:
  1. If no product exists with product ID 101, a new record is inserted.
  2. If a product with ID 101 already exists, 50 is added to the stock count (stock).

This allows you to update inventory efficiently in product management workflows.

Scenario 2: User Registration and Updates

In membership-based services, new users may register, and existing users may update their profiles. You can handle both cases with a single SQL statement.

Example

The following SQL statement inserts a new user or updates the name and email for an existing user.

INSERT INTO users (id, name, email)
VALUES (1, 'Ichiro Tanaka', 'tanaka@example.com')
ON DUPLICATE KEY UPDATE
name = 'Ichiro Tanaka',
email = 'tanaka@example.com';
  • Explanation:
  1. If there is no record with user ID 1, a new record is inserted.
  2. If a record with user ID 1 already exists, the name and email are updated.

This method is useful for centralized user data management.

Scenario 3: Updating Login History

Web applications commonly store login history. Let’s look at an example that registers a new user entry while also updating the last login timestamp for existing users.

Example

INSERT INTO login_history (user_id, last_login)
VALUES (1, NOW())
ON DUPLICATE KEY UPDATE
last_login = NOW();
  • Explanation:
  1. If there is no record with user_id = 1, a new record is inserted.
  2. If the user already exists, the last login timestamp (last_login) is updated to the current time (NOW()).

This SQL statement provides an efficient way to manage login information.

Scenario 4: Periodic Product Price Updates

If you need to update prices periodically, ON DUPLICATE KEY UPDATE lets you add new products and update existing product prices in one operation.

Example

INSERT INTO products (product_id, product_name, price)
VALUES (201, 'Smartphone', 69900)
ON DUPLICATE KEY UPDATE
price = VALUES(price);
  • Explanation:
  1. If no product exists with product_id = 201, a new product record is inserted.
  2. If it already exists, the product price (price) is updated.

This is a simple way to handle product price changes.

Scenario 5: Consolidating and Managing Imported Data

When importing data from external systems, you often need to prevent duplicates and keep the data consistent.

Example

INSERT INTO employees (employee_id, name, department)
SELECT id, full_name, dept
FROM external_employees
ON DUPLICATE KEY UPDATE
name = VALUES(name),
department = VALUES(department);
  • Explanation:
  1. Data is selected from the external_employees table and inserted into the employees table.
  2. If duplicates are detected, the name and department information are updated.

This kind of consolidation is important for data integration between systems.

Summary

These scenarios demonstrate how to manage data efficiently using INSERT ... ON DUPLICATE KEY UPDATE. Since these are common situations in real operations, use these examples as references and apply the appropriate SQL statements in your own work.

6. Important Notes and Best Practices

When using INSERT, UPDATE, and ON DUPLICATE KEY UPDATE in MySQL, understanding key precautions and applying best practices can significantly improve performance and ensure safe, efficient data operations. In this section, we introduce important considerations and recommended approaches for real-world use.

Important Notes

1. Always Specify the WHERE Clause Precisely

  • Problem: If you omit the WHERE clause in an UPDATE statement, all rows in the table may be updated.
  • Solution: Always define appropriate conditions in the WHERE clause to limit the affected rows.
UPDATE users
SET email = 'updated@example.com'
WHERE id = 1; -- Correct

2. Define Unique Keys Properly

  • Problem: If no unique key (PRIMARY KEY or UNIQUE index) exists when using ON DUPLICATE KEY UPDATE, an error will occur.
  • Solution: Define unique keys on columns that must not contain duplicate values.
ALTER TABLE users ADD UNIQUE (email);

3. Be Aware of AUTO_INCREMENT Behavior

  • Problem: When using ON DUPLICATE KEY UPDATE, the AUTO_INCREMENT value may increase even if a duplicate is detected.
  • Solution: Design your unique key structure carefully or manage ID values explicitly if AUTO_INCREMENT gaps are a concern.

4. Performance Considerations

  • Problem: Processing large amounts of data with INSERT or UPDATE can increase database load and slow down performance.
  • Solutions:
  • Use transactions to group operations efficiently.
  • Implement batch processing when necessary.

Best Practices

1. Use Transactions

To maintain data consistency, it is recommended to execute multiple operations within a transaction.

START TRANSACTION;

INSERT INTO users (id, name) VALUES (1, 'Taro Yamada')
ON DUPLICATE KEY UPDATE name = 'Taro Yamada';

UPDATE inventory SET stock = stock - 1 WHERE product_id = 101;

COMMIT;
  • Transactions allow you to roll back changes if an error occurs, ensuring data integrity.

2. Use Indexes Effectively

To improve INSERT and UPDATE performance, define appropriate indexes.

CREATE INDEX idx_user_email ON users (email);
  • Indexes speed up data retrieval, but excessive indexing may slow down INSERT and UPDATE operations—use them wisely.

3. Implement Proper Error Handling

Clearly defining error handling logic helps prevent unexpected behavior.

DELIMITER //
CREATE PROCEDURE insert_user(IN user_id INT, IN user_name VARCHAR(255))
BEGIN
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        SELECT 'An error occurred';
    END;
    START TRANSACTION;
    INSERT INTO users (id, name) VALUES (user_id, user_name)
    ON DUPLICATE KEY UPDATE name = user_name;
    COMMIT;
END;
//
DELIMITER ;

4. Set Default Values

Defining default values when designing tables reduces errors and clarifies which columns can be omitted during INSERT operations.

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255),
    status VARCHAR(20) DEFAULT 'active'
);

5. Handle Large Data Sets Carefully

When processing large volumes of data, limit the number of rows inserted or updated at once and divide operations into manageable batches.

INSERT INTO large_table (col1, col2)
VALUES
  (1, 'value1'),
  (2, 'value2'),
  ...
  (1000, 'value1000'); -- Choose an appropriate batch size

Common Pitfalls and Solutions

  • Pitfall 1: Mishandling Duplicate Data
    → Solution: Use unique keys and ON DUPLICATE KEY UPDATE appropriately.
  • Pitfall 2: Performance Degradation Due to Table Locks
    → Solution: Use indexes and transactions to limit the scope of processing.
  • Pitfall 3: Updating Unnecessary Columns
    → Solution: Restrict updates to only the required columns.

Summary

To use MySQL INSERT and UPDATE statements safely and efficiently, it is essential to understand key precautions and apply best practices. By properly using transactions, indexes, and error handling, you can improve both reliability and performance in database operations.

7. FAQ

In this section, we answer frequently asked questions about MySQL INSERT, UPDATE, and ON DUPLICATE KEY UPDATE. These explanations expand on earlier sections and help resolve common real-world concerns.

Q1: Why does the AUTO_INCREMENT value increase when using ON DUPLICATE KEY UPDATE?

Answer:
In MySQL, the AUTO_INCREMENT value is assigned when an INSERT operation is attempted. Even if a duplicate key is detected and the operation switches to an update (ON DUPLICATE KEY UPDATE), the AUTO_INCREMENT counter has already advanced. This is MySQL’s design behavior, and there is no way to prevent skipped AUTO_INCREMENT values.

Workaround:

  • If you need predictable ID values, consider managing IDs manually instead of using AUTO_INCREMENT.

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

Answer:

  • ON DUPLICATE KEY UPDATE: Updates the existing row when a duplicate key is detected. The original row remains intact.
  • REPLACE INTO: Deletes the existing row and inserts a new one when a duplicate key is detected. This may remove related foreign key references or historical data.

When to Use Each:

  • Use ON DUPLICATE KEY UPDATE if you want to preserve data history.
  • Use REPLACE INTO if you need to completely overwrite old data.

Q3: How can I insert multiple rows at once using INSERT?

Answer:
You can insert multiple rows in a single INSERT statement using the VALUES clause.

INSERT INTO users (name, email)
VALUES 
  ('Taro Yamada', 'taro@example.com'),
  ('Hanako Sato', 'hanako@example.com'),
  ('Jiro Suzuki', 'jiro@example.com');

This approach is more efficient than inserting rows one by one.

Q4: How do I specify multiple conditions in a WHERE clause?

Answer:
Use the AND or OR operators to combine multiple conditions.

UPDATE users
SET status = 'inactive'
WHERE last_login < '2024-01-01' AND status = 'active';
  • AND: Applies when both conditions are true.
  • OR: Applies when either condition is true.

Q5: When should I use transactions?

Answer:
Use transactions when data consistency is critical, such as:

  1. When multiple database operations must succeed together:
START TRANSACTION;
INSERT INTO orders (order_id, user_id) VALUES (1, 123);
UPDATE inventory SET stock = stock - 1 WHERE product_id = 101;
COMMIT;
  1. When you want to roll back changes if an error occurs:
    Transactions allow rollback to restore the original state in case of failure.

Q6: How can I efficiently handle large INSERT or UPDATE operations?

Answer:
Consider the following strategies:

  • Bulk operations: Insert multiple rows at once.
INSERT INTO users (name, email)
VALUES 
  ('Ichiro Tanaka', 'ichiro@example.com'),
  ('Hanako Sato', 'hanako@example.com');
  • Use indexes: Proper indexing improves search and update speed.
  • Divide processing: Execute operations in smaller batches instead of all at once.
UPDATE inventory
SET stock = stock - 1
WHERE product_id BETWEEN 100 AND 200;

Q7: What are the benefits of using default values?

Answer:
By defining default values, omitted columns in INSERT statements are automatically assigned predefined values. This simplifies code and helps prevent errors.

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255),
    status VARCHAR(20) DEFAULT 'active'
);

INSERT INTO users (name)
VALUES ('Taro Yamada'); -- status is automatically set to 'active'

Summary

This FAQ section addressed common practical questions. By applying these insights, you can use MySQL INSERT and UPDATE statements more accurately and efficiently in real-world scenarios.

8. Conclusion

In this article, we systematically explained the fundamental operations of the MySQL INSERT and UPDATE statements, as well as advanced techniques for managing data efficiently. Designed for beginners to intermediate users, this guide covered practical knowledge and best practices that are directly applicable in real-world scenarios.

Key Takeaways

  1. Basic Syntax of INSERT and UPDATE
  • We learned how to insert new data using INSERT and modify existing data using UPDATE.
  • Important considerations such as proper use of the WHERE clause and handling multiple rows were explained.
  1. Using ON DUPLICATE KEY UPDATE
  • We introduced ON DUPLICATE KEY UPDATE as an efficient technique to insert new data or update existing data within a single SQL statement.
  • Through examples like inventory management and login history updates, we demonstrated how it can be applied in real-world operations.
  1. Practical Use Cases
  • We presented SQL examples based on realistic scenarios such as e-commerce inventory management and user information updates.
  • These examples illustrate how to apply the concepts effectively in actual business workflows.
  1. Important Notes and Best Practices
  • We explained how to perform operations efficiently and safely by properly using the WHERE clause, ensuring data consistency with transactions, and leveraging indexes.
  1. FAQ for Deeper Understanding
  • By addressing common questions, we helped clarify practical concerns and deepen understanding for real-world use.

The Value You Gain from This Article

By accurately understanding and applying MySQL INSERT, UPDATE, and ON DUPLICATE KEY UPDATE, you can achieve the following benefits:

  • Improved Database Efficiency: Consolidate insert and update operations using concise SQL statements.
  • Error Prevention: Perform safe operations using proper WHERE clauses and transactions.
  • Stronger Practical Skills: Apply realistic examples directly to your own projects.

Next Steps

Use this article as a reference and start applying INSERT and UPDATE statements in your own projects. If you want to further enhance your skills, consider learning the following topics:

  • MySQL performance tuning
  • Building complex queries (subqueries and JOINs)
  • Using triggers and stored procedures in MySQL

We hope this guide helps you strengthen your MySQL data manipulation skills and improve productivity in your projects. Continue expanding your database knowledge and apply it effectively in your development work!