views:

159

answers:

4

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.

+3  A: 

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.

Ivo Sabev
thanks, appreciate it
Scarface
And, on top of that, if your check/delete operation isn't atomic (which a delete is), you run the risk of someone inserting after the check and before the delete (that you're not doing since your check is now working with stale information).
paxdiablo
+8  A: 

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.

DVK
Thanks DVK appreciate your response.
Scarface
You're welcome. And welcome to the wonderful world of database performance :)
DVK
A: 

Disregarding the time efficiency and the runtime and looking at the program readability, It is much easier to understand and logically easier to read if you have functions to check first if data is existing rather than directly calling the delete function. This way, you may add additional checking functionalities or confirmation options.

Hanseh
I'm going to disagree with you here. I think that a regular delete is pretty well understood to "succeed" even if no records are affected in set-based operation land. Plus, if you're going to check first, you introduce all kinds of transactional issues you'll have to worry about. And of course the performance hit...
Michael Haren
A: 

I think that a regular delete is pretty well understood to "succeed" even if no records are affected in set-based operation land.