karan
karan

Reputation: 300

Update the row if a particular column value differ, else insert new row

I have a table

UserId    Name    Age
1         Lisha   23
2         Ankur   21
3         Karan   22

For a particular given UserId, I want to update the age if the given age is different then the current age. Else if the UserId doesn't exists I want to insert a new row.

How can I do this in a single SQL statement.

Upvotes: 1

Views: 63

Answers (1)

Mureinik
Mureinik

Reputation: 311796

MySQL has a neat syntax that does exactly that, albeit it goes about it the opposite way - you define what you'd want to insert, and if a duplicate key error is generated, you define how you'd like to update the data instead:

INSERT INTO users
(userid, age)
ON DUPLICATE KEY UPDATE age = VALUES(age)

Upvotes: 1

Related Questions