INSERT INTO vs REPLACE INTO
The MySQL REPLACE statement is a MySQL extension to the SQL standard. The MySQL REPLACE statement works like the INSERT statement with the additional rules:
- If the record which you want to insert does not exist, the MySQL REPLACE inserts a new record.
- If the record which you want to insert already exists, MySQL REPLACE deletes the old record first and then insert a new record.
The first method is REPLACE. The syntax is the same as the INSERT function. When dealing with a record with a unique or primary key, REPLACE will either do a DELETE and then an INSERT, or just an INSERT. Now, this most likely isn’t the solution you need. This function will cause a record to be removed, and inserted at the end, which will cause the indexing to get broken apart, decreasing the efficiency of your table. If, however, you would require a different primary key with the new data, this may be your ideal solution. Here is the syntax
REPLACE INTO table(col1,col2,…) VALUES(val1,val2,…)
The second method is the ON DUPLICATE KEY UPDATE clause to the INSERT function. This one actively hunts down an existing record in the table which has the same UNIQUE or PRIMARY KEY as the one we’re trying to update. If it finds an existing one, you specify a clause for which column(s) you would like to UPDATE. Otherwise, it will do a normal INSERT. Here’s the syntax:
INSERT INTO table(col1,col2,…) VALUES(val1,val2,…)