Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL REPLACE Statement

The `REPLACE` statement in MySQL is used to insert or update data in a table. It functions similarly to `INSERT`, but it first deletes any existing row with the same primary key and then inserts the new row.

Usage

The `REPLACE` statement is used when you want to ensure that a row is replaced if a duplicate key exists. It is particularly useful for maintaining unique records when inserting data.

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

In this syntax, `REPLACE INTO` ensures that any existing row with the same unique key is removed before the new row is inserted.

Examples

1. Basic Replace

sql
REPLACE INTO users (id, username)
VALUES (1, 'johndoe');

In this example, if a row with `id` 1 exists in the `users` table, it will be deleted and replaced with a new row with the username 'johndoe'.

2. Replace with Multiple Columns

sql
REPLACE INTO products (product_id, name, price)
VALUES (101, 'Laptop', 999.99);

This syntax replaces a product with `product_id` 101 if it exists, otherwise adds a new entry with the specified name and price.

3. Replace with Subquery

sql
REPLACE INTO inventory (item_id, quantity)
SELECT item_id, SUM(quantity) FROM incoming_items
GROUP BY item_id;

In this example, `REPLACE` is used with a subquery to update or insert records from the `incoming_items` table into the `inventory` table.

Tips and Best Practices

  • Ensure unique constraints. Use `REPLACE` only when your table has a primary key or unique index, as it relies on these to identify duplicates.
  • Be cautious of data loss. Remember that `REPLACE` deletes the existing row before inserting the new one, which can lead to unintended data loss.
  • Consider transaction usage. Use transactions if multiple related changes must occur simultaneously to ensure data integrity.
  • Evaluate performance impacts. Frequent use of `REPLACE` can lead to overhead due to the delete operation; consider using `INSERT ON DUPLICATE KEY UPDATE` as an alternative.
sql
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON DUPLICATE KEY UPDATE column1 = value1, column2 = value2;

This syntax allows updating specific columns without deleting the existing row, which can be more efficient in certain scenarios.

  • Trigger Effects. Be aware that using `REPLACE` will activate any DELETE triggers associated with the table, which may not be immediately obvious.