How can MySQL achieve updating data if it already exists or adding it if it doesn’t?

You can use the INSERT…ON DUPLICATE KEY UPDATE statement to update data if it exists or add data if it doesn’t.

Assuming we have a table named users, with columns id, name, and age, where id is the primary key. Now we need to check if the data exists based on the id – if it does, then update the name and age; if it doesn’t, then add new data.

You can achieve this using the following statement:

INSERT INTO users (id, name, age)
VALUES (1, 'John', 25)
ON DUPLICATE KEY UPDATE name = VALUES(name), age = VALUES(age);

In the example above, we attempt to insert data with an id of 1. If that id already exists, the values for name and age will be updated to ‘John’ and 25; if the id does not exist, a new data entry will be inserted.

Before using this statement, it is necessary to add a primary key constraint or unique index to the ID column to ensure its uniqueness.

bannerAds