The REPLACE INTO
function in MySQL works in such a way that it deletes and inserts the row. In my table, the primary key (id
) is auto-incremented, so I was expecting it to delete and then insert a table with id
at the tail of the database.
However, it does the unexpected and inserts it with the same id
! Is this the expected behaviour, or am I missing something here? (I am not setting the id
when calling the REPLACE INTO
statement)
The REPLACE statement in MySQL is an extension of the SQL Standard. This statement works the same as the INSERT statement, except that if an old row matches the new record in the table for a PRIMARY KEY or a UNIQUE index, this command deleted the old row before the new row is added.
To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key. Note You must be logged in to the database using a database name before you can add a primary key or conduct any other referential integrity (RI) operation.
This is an expected behavior if you have another UNIQUE
index in your table which you must have otherwise it would add the row as you would expect. See the documentation:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.
https://dev.mysql.com/doc/refman/5.5/en/replace.html
This really also makes lot of sense because how else would mySQL find the row to replace? It could only scan the whole table and that would be time consuming. I created an SQL Fiddle to demonstrate this, please have a look here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With