Home Insert into a MySQL table or update if exists
Reply: 0

Insert into a MySQL table or update if exists

user6143 Published in September 19, 2018, 11:01 am

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example,

insert into table (id, name, age) values(1, "A", 19)

Let’s say the unique key is id, and in my database there is a row with id = 1. In that case I want to update that row with these values. Normally this gives an error. If I use insert IGNORE it will ignore the error, but it still won’t update.

share|improve this question
  • SQL needs an official syntax for this use case that doesn't force duplication of values in the syntax and preserves the primary key. – Pete Alvin Jan 26 at 13:02

9 Answers 9

active oldest votes
up vote 1312 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.379938 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO