SQL query - update if exists, insert otherwise

I need to write a SQL query for MySQL so that the row is updated if it exists, but inserted if it is not.

i.e.

If the string exists ...

UPDATE Table1 SET (...) WHERE Column1='SomeValue' 

If it does not exist ...

 INSERT INTO Table1 VALUES (...) 

Can this be done in one request?

+4
source share
2 answers

I believe you need to undo your logic for it to work:

insert into the table - if it exists (the same key), then update it.

this can be achieved using the ON DUPLICATE as follows:

 INSERT INTO Table1 VALUES(...) ON DUPLICATE KEY UPDATE column=column+1 

check the manual here

+12
source

Use the syntax INSERT... ON DUPLICATE KEY UPDATE .

See manual

(For search purposes, by the way, this is usually called "upsert")

+7
source

Source: https://habr.com/ru/post/1343610/


All Articles