2

I have simple table like this:

+----------+---------------+-------------+
| ID (int) | KEY (varchar) | VALUE (int) |
+----------+---------------+-------------+
|        1 | asdf          |         100 |
|        2 | fdsa          |         321 |
|        3 | ecda          |         211 |
+----------+---------------+-------------+

and I want to update row where KEY = 'something' but if there is no row where KEY = 'something' I want to INSERT new row:

+----------+---------------+-------------+
| ID (int) | KEY (varchar) | VALUE (int) |
+----------+---------------+-------------+
|        1 | asdf          |         100 |
|        2 | fdsa          |         321 |
|        3 | ecda          |         211 |
|        4 | something     |         200 |
+----------+---------------+-------------+

Is it possible in only one query?

OMG Ponies
  • 314,254
  • 77
  • 507
  • 490
Michal
  • 3,496
  • 7
  • 44
  • 70

2 Answers2

7

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

peterm
  • 88,818
  • 14
  • 143
  • 153
6

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'
ELSE
    INSERT INTO Table1 VALUES (...)
Fabian Bigler
  • 9,721
  • 6
  • 41
  • 64