Syed Syed - 2 months ago 12
SQL Question

Update MySQL row instead of insert if value in a column already exists?

I have a sql query

INSERT INTO names ('name','mobile','timestamp') VALUES ('my name','123456','2016-10-08 17:59:54')


Here mobile field is unique, I want if mobile number provided already exists in the database only the name and timestamp should be updated?

Answer

You want ON DUPLICATE KEY UPDATE:

INSERT INTO names (name, mobile, timestamp)
    VALUES ('my name', '123456', '2016-10-08 17:59:54')
    ON DUPLICATE KEY UPDATE name = VALUES(name), timestamp = VALUES(timestamp);

I assume the single quotes around the column names in the query in the question are just typos.