tags:

views:

353

answers:

3

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?

A: 

It depends on what the primary key and/or unique constraints are on the table. If there is no primary key or unique contraints, it is no different from a basic INSERT statement.

The documentation gives a reasonably clear explanation: http://dev.mysql.com/doc/refman/5.0/en/replace.html

Daniel Renshaw
A: 

There are two different operators for insert and update

update tblNames set FirstName="John", LastName="Smith" where FirstName="John" and LastName="Jones"

this will rename John Jones to John Smith

insert into tblNames (FirstName, LastName) values ("John", "Smith")

this will add a new entry (but may fail if there is already John Smith in the table and there is a unique constraint on FirstName/LastName)

UserControl
When i was answering there was no "mysql" tag, so my code samples are standard SQL
UserControl
Is there a way to avoid the error on the insert if the record already exists?
Matt
You can perform 'select' to check if the entry already exists before doing update or insert. Not sure about MySQL but in SQL Server you can even avoid the select. The typical scenario:update tblNames set ... where key-conditionif @@rowcount = 0 -- the number of rows affected by the last statement (i.e. update) insert into tblNames ....sorry, for the late answer, hope this helps
UserControl
+1  A: 
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.

Quassnoi
If you're using `REPLACE INTO` to only insert some of the columns in a row, you should really be using `INSERT INTO ... ON DUPLICATE KEY UPDATE` otherwise you'll find those columns you didn't specify in your `REPLACE INTO` statement are blank due to the `DELETE` `INSERT` steps involved in `REPLACE`. http://dev.mysql.com/doc/refman/5.0/en/replace.html
Greg K
So if John Smith is in the table, and I send John Jones, what sql command to I use so that it Inserts John Jones, but if I send John Smith, it does nothing.
Matt
@Matt: please post the output of `SHOW CREATE TABLE tblNames`
Quassnoi
@Quassnoi: There is not table yet.. This is hypothetical planning :)
Matt