I often have to check a table column before performing an update, insert, or delete in mysql. I’m wondering if this is redundant because the mysql WHERE clause is already a condition.
Example:
-
A database table named
private_messagesstores private messages for
users. -
A column named
readhas a default value of0and updates to1
when a user has read a message.
Which one of the two methods is most efficient and accurate for updating the table?
Perform a query, return the value of read, and use an if condition:
if (read == 0) //if user did not read message
{
UPDATE private_messages
SET read = 1
WHERE id = 48 //the unique, auto increment index
}
Or simply add a WHERE AND clause to the query:
UPDATE private_messages
SET read = 1
WHERE id = 48
AND read = 0
and use mysql_affected_rows() to determine if a row was updated.
Edit: Another situation could be deleting a row if a column has a certain value. Should I use if condition or where?
If you alread have the
readvariable in memory (ie, queried for other purposes), I would choose the first method, as if the message is not read, you won’t need to query the database.If you don’t have the
readvariable in memory, use the second method, has it will only query the DB one time.