๐Ÿ”€ MySQL Upsert Logic โ€“ INSERT or UPDATE in One Command


๐Ÿงฒ Introduction โ€“ Why Use Upsert in MySQL?

In MySQL, upsert logic allows you to insert a new row or update an existing one if a duplicate key is found. It’s commonly needed when:

  • ๐Ÿ”„ Inserting new records with fallback update
  • ๐Ÿงฎ Maintaining counters or aggregates
  • ๐Ÿ“ฆ Syncing data from external systems
  • ๐Ÿ” Avoiding duplication while preserving integrity

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to implement upsert logic using INSERT ... ON DUPLICATE KEY UPDATE
  • Use of REPLACE INTO and its caveats
  • Practical examples and best practices

๐Ÿ”„ 1. INSERT … ON DUPLICATE KEY UPDATE

This is the preferred method of implementing upserts in MySQL.


๐Ÿ”น Syntax

INSERT INTO table (columns...)
VALUES (values...)
ON DUPLICATE KEY UPDATE column = value;

๐Ÿ”น Example โ€“ Insert or Update Product Stock

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

โœ… If product_id = 101 exists, quantity increases by 5
โœ… If not, a new row is inserted


๐Ÿ”น Requirements

  • Table must have a PRIMARY KEY or UNIQUE KEY
  • The ON DUPLICATE KEY UPDATE clause only triggers if there’s a duplicate violation

๐Ÿ” 2. REPLACE INTO โ€“ Alternative Upsert

This command first deletes the existing row and then inserts the new one.


๐Ÿ”น Syntax

REPLACE INTO table (columns...)
VALUES (values...);

๐Ÿ”น Example

REPLACE INTO users (id, name)
VALUES (1, 'Alice');

โœ… If id = 1 exists, the row is deleted and reinserted

โš ๏ธ Caution: Auto-increment, foreign keys, and triggers may behave unexpectedly.


๐Ÿ” INSERT vs REPLACE vs UPSERT

OperationBehavior
INSERTFails on duplicate key
REPLACEDeletes existing row, then inserts new one
INSERT ... ON DUPLICATE KEYUpdates existing row without delete
MERGEโŒ Not available in MySQL (but supported in other RDBMS like SQL Server)

๐Ÿงช Real-World Use Case โ€“ Track Login Timestamps

CREATE TABLE login_audit (
  user_id INT PRIMARY KEY,
  last_login DATETIME
);
INSERT INTO login_audit (user_id, last_login)
VALUES (123, NOW())
ON DUPLICATE KEY UPDATE last_login = NOW();

โœ… Logs login time whether it’s the first login or a repeat.


๐Ÿ’ก Best Practices

โœ… Tip๐Ÿ’ก Why It Matters
Use unique or primary keys for upsertsDetermines when to update instead of insert
Avoid REPLACE with complex relationshipsMay trigger delete-side effects
Be explicit in update clausePrevents unintended overwrites
Use VALUES(col) or NEW.col in updatesReuse inserted values easily
Monitor auto-increment with REPLACEREPLACE may generate new IDs due to DELETE-INSERT

๐Ÿ› ๏ธ Advanced Example โ€“ Maintain Aggregate Score

INSERT INTO leaderboard (user_id, score)
VALUES (7, 10)
ON DUPLICATE KEY UPDATE score = score + 10;

โœ… Increases score if user exists, otherwise inserts new user.


๐Ÿ“˜ Common Use Cases

ScenarioUpsert Strategy Used
Count email opens per userON DUPLICATE KEY UPDATE counter = counter + 1
Log user session tokensREPLACE INTO sessions (...) VALUES (...)
Update cart item quantityON DUPLICATE KEY UPDATE quantity = quantity + X
Merge product feedsINSERT ... ON DUPLICATE KEY UPDATE price = VALUES(price)

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

MySQLโ€™s upsert logic using INSERT ... ON DUPLICATE KEY UPDATE and REPLACE INTO enables efficient conflict-free inserts and updates in a single command.

๐Ÿ” Key Takeaways

  • Use INSERT ... ON DUPLICATE KEY UPDATE for safe, non-destructive upserts
  • Use REPLACE INTO only when you’re okay with delete-then-insert behavior
  • Ensure a UNIQUE or PRIMARY KEY exists on conflict columns
  • Upsert logic reduces the need for complex SELECT before INSERT patterns

โš™๏ธ Real-World Relevance

Used in user tracking, product syncing, queue systems, activity logging, and web applications with high-frequency inserts and updates.


โ“ FAQ โ€“ MySQL Upsert Logic


โ“ Does ON DUPLICATE KEY UPDATE require a unique key?

โœ… Yes. It triggers only when a PRIMARY KEY or UNIQUE INDEX conflict occurs.


โ“ Is REPLACE INTO the same as UPSERT?

๐Ÿšซ No. REPLACE INTO deletes and reinserts the rowโ€”itโ€™s more like DELETE + INSERT.


โ“ Can I update multiple columns on conflict?

โœ… Yes:

ON DUPLICATE KEY UPDATE col1 = VALUES(col1), col2 = VALUES(col2);

โ“ Can I use ON DUPLICATE KEY without a primary or unique key?

โŒ No. Without a conflict condition, the UPDATE clause wonโ€™t trigger.


โ“ Is MERGE available in MySQL?

โŒ No. MERGE is not part of MySQL. Use upsert logic instead.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ”€ MySQL Upsert Logic

Or Copy Link

CONTENTS
Scroll to Top