views:

1350

answers:

2

Is there an easy way to INSERT an row when not exists, or to UPDATE if it exists, using one MySQL query?

+15  A: 

Yes, INSERT ... ON DUPLICATE KEY UPDATE. For example:

INSERT INTO `usage`
(`thing_id`, `times_used`, `first_time_used`)
VALUES
(4815162342, 1, NOW())
ON DUPLICATE KEY UPDATE
`times_used` = `times_used` + 1
chaos
Wow, that's awesome. Do other RDMSs have this feature?
Brian Ramsay
Yeah, I believe SQL Server's equivalent is called `MERGE`. In general, the concept is often referred to as `"UPSERT"`.
chaos
blub
Make a unique index on GEB and Topic
Chacha102
If you're running tables without keys then you have bigger problems than trying to save 1 query per execution (which is all this will do, as it bypasses doing a SELECT to check if exists)
iAn
@blub: If you create a unique key on `geb` and `topic` it will work (`ALTER TABLE table ADD UNIQUE geb_by_topic (geb, topic)`).
chaos
I didn't enter a prim.key because i then had to use a new column cause geb and topic are both not unique.I didn't know it was possible to make a key pairing two columns!!Thanx chaos.
blub
@Brian: Oracle's equivalent is also called `MERGE` but I'm not sure if its syntax is identical to SQL Server's.
Ken Keenan
@iAn: That isn't really all it does. If you check for existence using a `SELECT`, then perform an `INSERT`, you have concurrency issues that don't exist if you're using an `ON DUPLICATE KEY UPDATE`.
chaos