MySQL
database
SQL query
insert if not exists
database management

How can I do 'insert if not exists' in MySQL?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Inserting data into a database is a common task in application development, and sometimes you only want to insert a new record if it doesn't already exist. This is often referred to as an "insert if not exists" operation. In MySQL, there are a few strategies to handle this pattern. This article will delve into these methods and explore their advantages and disadvantages.

Table of Contents

  1. Using INSERT IGNORE
  2. Using ON DUPLICATE KEY UPDATE
  3. Using REPLACE
  4. Using Subqueries
  5. Summary Table
  6. Conclusion

1. Using INSERT IGNORE

One approach to accomplish an "insert if not exists" operation is by using the INSERT IGNORE statement. This allows the insertion of a new row but ignores the insert if the row already exists.

sql
1CREATE TABLE Users (
2    id INT NOT NULL PRIMARY KEY,
3    username VARCHAR(255) UNIQUE,
4    email VARCHAR(255)
5);
6
7INSERT IGNORE INTO Users (id, username, email) VALUES (1, 'johndoe', '[email protected]');

Explanation:

  • Behavior: INSERT IGNORE modifies the default error handling. Instead of throwing an error if a duplicate key is found, it proceeds with a warning. This is helpful when only interested in inserting unique records.
  • Consideration: While straightforward, INSERT IGNORE can silently ignore actual errors (e.g., data type mismatches), not just duplicates. It's crucial to also be aware of other ignored issues.

2. Using ON DUPLICATE KEY UPDATE

Another method is using INSERT ... ON DUPLICATE KEY UPDATE. This statement allows you to update an existing record when a duplicate key is found.

sql
INSERT INTO Users (id, username, email)
VALUES (2, 'janedoe', '[email protected]')
ON DUPLICATE KEY UPDATE id=id;

Explanation:

  • Behavior: If a row is inserted without conflict, it proceeds as usual. If a duplicate key is found, the UPDATE is performed.
  • Flexibility: By setting id=id, you effectively do nothing on duplication, making this method act as a "do-nothing" if the row exists.
  • Performance: This method may be slightly less efficient than others because it involves an UPDATE.

3. Using REPLACE

The REPLACE statement is another option that effectively deletes a row with a matching unique key and then inserts the new record.

sql
REPLACE INTO Users (id, username, email) VALUES (3, 'mike', '[email protected]');

Explanation:

  • Behavior: If a row with a given unique key exists, REPLACE will delete the row and insert the new data. If the key does not exist, it performs as an INSERT.
  • Consideration: Be cautious as this approach deletes and re-inserts data, which may have side effects like triggering delete triggers or causing the loss of foreign key dependencies.

4. Using Subqueries

For more control over the process, you can utilize a subquery to check for the existence of a record before doing an insert.

sql
INSERT INTO Users (id, username, email)
SELECT 4, 'janesmith', '[email protected]' FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM Users WHERE username = 'janesmith');

Explanation:

  • Behavior: The WHERE NOT EXISTS clause ensures the insert only happens if the subquery returns no existing records.
  • Flexibility and Performance: This method is more flexible for more complex conditions but might not perform as well on very large datasets without appropriate indexing.

5. Summary Table

The below table summarizes the advantages and disadvantages of each method:

MethodAdvantagesDisadvantages
INSERT IGNORESimple implementationIgnores all errors—not just duplicates.
ON DUPLICATE KEY UPDATEFlexibility to define actions on conflictMay affect performance due to UPDATE.
REPLACEStraightforward implementationDeletes and re-inserts, possibly triggers.
SubqueriesHighly flexible and expressiveMore complex and potentially slow.

6. Conclusion

Choosing the right method depends on your specific use case. INSERT IGNORE may suit applications where the primary concern is unique entry presence without caring about other warning factors. ON DUPLICATE KEY UPDATE is ideal when you want to make a decision on key conflict. Subqueries offer great flexibility for conditional inserts but come with a performance trade-off. Understanding these nuances will allow you to make the optimal choice for your MySQL operations, ensuring both data integrity and performance efficiency.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.