Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to always run a delete query, or to check if that information exists first

Is it more efficient to always run a DELETE query by default whether an entry exists or not, for example to delete a user name after a certain period of time (DELETE * from table WHERE username='user'), or should you first check if the rows to be deleted exist using a SELECT query and checking mysql_num_rows.

What uses more processor resources on the server side?

Obviously one approach contains more code, but I was wondering if certain mysql operations used a lot more CPU than others.

like image 413
Scarface Avatar asked Apr 09 '10 03:04

Scarface


2 Answers

Delete is more efficient since the system takes as much time (and literally do exactly the same work) finding rows to delete as it would have on select.

However, if you wish to have special logic kick in if zero rows were deleted, you can use ROW_COUNT() function and check if it's zero after the delete.

Also, see the related answer here.

like image 169
DVK Avatar answered Nov 14 '22 23:11

DVK


There is no need to check, because the MySQL will do that check for you anyway. Checking will be one more extra query which you don't really need, because of the way DELETE works it is already a checking query by itself and if found record will be deleted.

like image 22
Ivo Sabev Avatar answered Nov 14 '22 23:11

Ivo Sabev