MySQL "good" way to insert a row if not found, or update it if it is found
You can use "REPLACE INTO" or "INSERT… ON DUPLICATE KEY UPDATE". I believe the second is what you want, but there are situations where REPLACE INTO is convenient.
From my other Stack Overflow answer:
If you want to do this in a single statement, I would recommend using the INSERT ... ON DUPLICATE KEY UPDATE
syntax, as follows:
INSERT INTO table (id, someothervalue) VALUES (1, 'hi mom') ON DUPLICATE KEY UPDATE someothervalue = 'hi mom';
The initial INSERT
statement will execute if there is no existing record with the specified key value (either primary key or unique). If a record already exists, the following UPDATE
statement (someothervalue = 3
) is executed.
This is supported in all versions of MySQL. For more info, see the MySQL Reference Manual page for INSERT ... ON DUPLICATE KEY UPDATE
This is called an UPSERT (UPdate or inSERT). There are a number of SO questions about it you can search for. See Wikipedia
EDIT: MySQL 4.1+ supports INSATE (INSert or updATE), which should get you the same thing, as long as you have a primary key. MySQL Manual