Skip to content Skip to sidebar Skip to footer

If Exists Update Else Insert In One Query

I have simple table like this: +----------+---------------+-------------+ | ID (int) | KEY (varchar) | VALUE (int) | +----------+---------------+-------------+ | 1 | asdf

Solution 1:

You can utilize ON DUPLICATE KEY UPDATE

INSERT INTO yourtable (`id`, `key`, `value`) VALUES (4, 'something', 200)
ON DUPLICATE KEY UPDATE `value` = 200; 

key column should have UNIQUE index on it

SQLFiddle

Solution 2:

Yes, that's pretty simple.

This is what you are looking for:

IF EXISTS (SELECT*FROM Table1 WHERE Column1='SomeValue')
    UPDATE Table1 SET (...) WHERE Column1='SomeValue'ELSEINSERTINTO Table1 VALUES (...)

Post a Comment for "If Exists Update Else Insert In One Query"