Cover Image for MySQL UPSERT
120 views

MySQL UPSERT

The term upsert refers to the operation of inserting a new record into a database table if it doesn’t exist or updating an existing record if it does. In MySQL, you can perform an upsert operation using the INSERT INTO ... ON DUPLICATE KEY UPDATE statement or by using the INSERT IGNORE statement.

Here’s how you can use both methods for upserts:

  1. INSERT INTO … ON DUPLICATE KEY UPDATE: This method allows you to specify what to do when a duplicate key violation occurs. If the key (e.g., a primary key or unique constraint) exists in the table, it will update the existing record; otherwise, it will insert a new one.
   INSERT INTO table_name (column1, column2, ...)
   VALUES (value1, value2, ...)
   ON DUPLICATE KEY UPDATE
   column1 = value1, column2 = value2, ...;

Here’s an example:

   INSERT INTO users (user_id, username, email)
   VALUES (1, 'john_doe', '[email protected]')
   ON DUPLICATE KEY UPDATE
   username = 'john_doe', email = '[email protected]';

If a record with user_id 1 already exists, this query will update the username and email columns. If no such record exists, it will insert a new one.

  1. INSERT IGNORE: The INSERT IGNORE statement allows you to insert a new record into a table. If a duplicate key violation occurs, it will ignore the error and skip the insert operation.
   INSERT IGNORE INTO table_name (column1, column2, ...)
   VALUES (value1, value2, ...);

Here’s an example:

   INSERT IGNORE INTO users (user_id, username, email)
   VALUES (1, 'john_doe', '[email protected]');

If a record with user_id 1 already exists, this query will be ignored, and no changes will occur.

It’s important to note that the behavior of the upsert operation depends on the specific key constraints and the primary key of the table. Ensure that the table has appropriate indexes and constraints for the upsert operation to work as intended. Also, consider using the ON DUPLICATE KEY UPDATE method if you need to perform an upsert with updates.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS