Inserting and Replacing Data Using REPLACE

The REPLACE statement works similarly to INSERT. It always tries to insert the new data, but when it tries to insert a new row with the same primary or unique key as an existing row, it deletes the old data and replaces it with the new.

It takes the following format:

REPLACE [LOW PRIORITY | DELAYED]
  [INTO] table_name
  SET column_name1=expression1, column_name2=expression2,...

or

REPLACE [LOW PRIORITY | DELAYED]
  [INTO] table_name [(column_name,...)]
  VALUES (expression,...),(...)...

or

REPLACE [LOW PRIORITY | DELAYED]
  [INTO] table_name [(column_name,...)]
  SELECT...

To illustrate how to use REPLACE, suppose that we have data in the subscribers table that looks like this:

 +---------------+-----------------+---------------------------+ ...

Get Sams Teach Yourself MySQL in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.