O'Reilly logo

Sams Teach Yourself MySQL by Chris Newman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The REPLACE Statement

The REPLACE statement works just like INSERT, except that if a row already exists in the table with the same PRIMARY KEY value as the new data, the new row replaces it. Therefore, REPLACE never causes a PRIMARY KEY violation.

The syntax for REPLACE is just like INSERT, or you can use the alternative syntax with SET, if you prefer. The following examples both perform the same operation: to replace the MINI product with a new description, weight, and price.

mysql> REPLACE INTO products
    -> (product_code, name, weight, price)
    -> VALUES ('MINI', 'Mini produt', '1.25', 3.99);
Query OK, 2 rows affected (0.00 sec)
mysql> REPLACE INTO products
    -> SET product_code = 'MINI',
    ->     name = 'Mini product',
    ->     weight = 1.25,
    ->     price = ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required