32

When updating a table in MySQL, for example:

Table user

user_id | user_name

1         John
2         Joseph
3         Juan

If I run the query

UPDATE `user` SET user_name = 'John' WHERE user_id = 1

Will MySQL write the same value again or ignore it since it's the same content?

2
  • If this is about performance (i.e. there being a benefit to try being clever and avoiding this) it is a good thing to know. But I would not make application code depend on what gets returned for the "rows affected" count. Commented Feb 12, 2016 at 13:53
  • Related: stackoverflow.com/questions/13559583/… (please answer that one, too, if you can) Commented Feb 12, 2016 at 13:57

1 Answer 1

50

As the MySQL manual for the UPDATE statement implies,

If you set a column to the value it currently has, MySQL notices this and does not update it.

So, if you run this query, MySQL will understand that the value you're trying to apply is the same as the current one for the specified column, and it won't write anything to the database.

Sign up to request clarification or add additional context in comments.

5 Comments

Tho I wonder if it's a good function, speaking of performance. If someone else desire to answer providing more details it would be great!
does MySQL throws something back saying can't update because of same value or It says nothing, because when I am trying this, it returns 0 , 0 means what here? that can't update same data or nothing has done or if there is any server related issue then it will also return 0 right ?
When executing statements MySQL will return two values, (last_inserted_id, rows_affected) that's what the 0,0 you're getting means, the statement was executed but it inserted nothing and updated nothing
How would you find out which columns updated when some are the same value?
The result value 0 in this case is the worst! It forces some strange workarounds in dev with pre-selects or pre-inserts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.