Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query- Update if exists, insert otherwise

Tags:

sql

mysql

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

i.e.

If row exists...

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

If it does not exist...

INSERT INTO Table1 VALUES (...)

Can this be done in one query?

like image 223
Urbycoz Avatar asked Mar 14 '11 09:03

Urbycoz


2 Answers

i believe you need to reverse your logic in order for it to work:

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

this can be achieved by the ON DUPLICATE statement like so:

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

check the manual here

like image 194
BigFatBaby Avatar answered Oct 27 '22 01:10

BigFatBaby


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

See the manual

(For searching purposes, btw, this is usually referred to as an "upsert")

like image 32
froadie Avatar answered Oct 27 '22 01:10

froadie