The question is should I bother with a record count i.e., SELECT count(*) to see if there're any events to delete or should I just go ahead with the delete command. Is there any advantage one over the other or is there a better way to execute this?
I added 1000 records of average size (all the same). Ran a count - timed the code and then ran a delete - timed that code.
The count took 0.008831 seconds
The delete took 0.421286 seconds
Nearly a half second for 1000 records.
- There are no records: In this case, surely you can spare the fraction of a second longer that it may take to delete no records compared to counting zero records. This amount of time will never grow, so you can always depend on being able to deal with it.
- There are a ton of records: Do you really want to run through that table twice? You're going to have to delete them, so why count at all? Plus, this option grows with your data, so you can't really assume that it's a tolerable amount of time to wait.
Therefore, I recommend that you don't count the records first.
That being said, I will recall for you one piece of advice: optimize for the case that is expected to be the most common.
Hope it helps.
Thinking outloud here:
I haven't changed it yet simply because I was wondering the same thing - actually waffling. I did review my indexes to see if I had them set up right because indexes will significantly affect performance. Since we're talking events - the dates are indexed and that fits the needs of the delete code.
My test was based on 1000 records and I saved roughly 0.4 seconds. We're talking a small community calendar here. There aren't that many events in a year let alone a single day. But if I were to port the code to another website where I use it to, let's say, transfer completed orders from a 'Pending Orders' table to a 'Completed Orders' table, I could conceivably have records in the thousands.
All that being said, though logically I can see your point amoore, I have to wonder two things: did I test the count(*) correctly (is there more of a time savings than I think I found?) and why was count created - what did the good folks at MySQL have it earmarked for?
1.
"SELECT X FROM Y WHERE Z";
$Result=mysql_query( $sql , $db_connection );
$number = mysql_num_rows($Result);
if($number > 0)
{
do delete
}
2.
"SELECT COUNT(*) FROM X WHERE Z";
$Result=mysql_query( $sql , $db_connection );
######
this bit eludes me, how do I use $Result (my stupid bit)
######
if.....statement
Cheers