MySQL: UPSERT using REPLACE

Profile picture for user arilio666

Here in REPLACE two scenarios take place:

  1. The following query replaces or makes changes to the existing matching input we provide.
  2. If there is no match it will simply perform the insertion.

Syntax

REPLACE INTO Table(ColumnNames)   
VALUES (Values to be inserted); 

Example 

REPLACE INTO upsert_example(ID, Name, Alias, Status)   
VALUES (4,'May', 'Aunt', 'Alive'); 

Here I have changed status from deceased to alive simply replaced the value.

Let us see what happens when there is no match to replace value.

REPLACE INTO upsert_example(ID, Name, Alias, Status)   
VALUES (6,'Blue', 'black', 'Alive'); 

  • Since there was no match the value got inserted instead of replaced.
  • If you have noticed when we replace status what is happening here is it is deleting the entire record and replacing the whole record with the provided update this is how to REPLACE works.
Tags