MySQL: Know when to UPDATE and when to INSERT?

I am still very new to mySQL, so I would like to get it right to avoid future failures.

What is the correct way to determine when I need a UPDATE

record in a table or a INSERT

new one?

Thanks.

+2


a source to share


3 answers


If you want to insert a record if the value does not exist in a specific column, or update it when it does exist, you must declare a constraint UNIQUE

on the column and use this syntax:



INSERT
INTO    mytable (key, value)
VALUES  ($newkey, $newvalue)
ON DUPLICATE KEY UPDATE
SET     value = $newvalue

      

+3


a source


Well, this question is very incomplete. This is not a question about the database, but about your application logic. You need to know when you create something new (add a user to your application) and when you change an existing record (by changing the specific information about that user).



Perhaps you should ask about your specific problem.

+2


a source


Pay attention to REPLACE INTO or INSERT., ON DUPLICATE KEY .

+1


a source







All Articles