Often I want to add a value to a table or update a value if its key already exists. This can be done in several ways, assuming that the primary or unique key is specified in the columns "user_id" and "pref_key" in the example:
1. Blind insert, update upon receipt of a duplicate key error:
// Try to insert as a new value
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If a duplicate-key error occurs run an update query
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
2. Check availability, then select or update:
// Check for existence
SELECT COUNT(*)
FROM my_prefs
WHERE user_id=1234 AND pref_key='show_help';
// If count is zero, insert
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If count is one, update
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
The first method seems to be preferable, since only one request for new insertions and two for updating will be required for updating, moreover, since the second method always requires two requests. Is there something I am missing out on, although it would be a bad idea to blindly insert?
source
share