Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Replace Into question

Tags:

replace

sql

mysql

With Replace Into, if I have two fields. FirstName LastName. The table has John Smith in it, if I was to run REPLACE INTO tblNames (FirstName, LastName) VALUES (John, Jones) Would that replace Smith with Jones, or create a new name?

What determines if its an Update or and Insert?

like image 921
Matt Avatar asked Apr 30 '10 09:04

Matt


1 Answers

REPLACE
INTO    tblNames (FirstName, LastName)
VALUES  ('John', 'Jones')

If there a unique constraint of any kind on FirstName, LastName or their combination, and it is violated, the records gets deleted and inserted with the new values.

The record will be replaced if any of the conditions is satisfied:

  • FirstName is UNIQUE and there is a John in the table,
  • LastName is UNIQUE and there is a Jones in the table,
  • FirstName, Lastname is UNIQUE and there is a John Jones in the table.

Note that REPLACE operation is an INSERT possibly following a DELETE which will always affect the table.

In the newer versions of MySQL, you should use INSERT … ON DUPLICATE KEY UPDATE.

like image 74
Quassnoi Avatar answered Oct 11 '22 06:10

Quassnoi