Skip to main content

How to create a mysql query that checks if a row exists - if it does I want to insert a new record otherwise increment a value

I have a table which has an ID and an occurrences column. I want to create a single transaction to the db where

if ID exists in DB:
    occurrences++
else:
    insert new row where occurrences = 1

I saw that it's possible to do an IF THEN statement so I was attempting to do something like this:

IF ID = 123 IS NOT NULL THEN
    UPDATE occurrences = occurrences +1
ELSE
    INSERT INTO entity_table(123, 1)
END IF;
Answer
INSERT INTO entity_table SET id=123, occurrences = 1
ON DUPLICATE KEY UPDATE occurrences = occurrences + 1

Comments