You should use
Merge Queries
a Merge query is a combination of an Insert query and an Update query. If a given condition is met, such as a row with a given primary key already existing, then an Update query is run. If not, an Insert query is run.
The above is for drupal
If you are using mysql then you can use UPDATE
or ON DUPLICATE KEY UPDATE