In the case when I want to check, if a certain entry in the database exists I have two options.
I can create an sql query using COUNT() and then check, if the result is >0…
…or I can just retrieve the record(s) and then count the number of rows in the returned rowset. For example with $result->num_rows;
What’s better/faster? in mysql? in general?
Just tested, works fine on MySQL v5
COUNT(*) is generally less efficient if:
If you are COUNT’ing based on a WHERE clause that is guaranteed to produce a single record (or 0) and the DBMS knows this (based upon UNIQUE indexes), then it ought to be just as efficient. But, it is unlikely that you will always have this condition. Also, the DBMS may not always pick up on this depending on the version and DBMS.
Counting in the application (when you don’t need the row) is almost always guaranteed to be slower/worse because:
Of course, if you want to DO something with the row if it exists, then it is definitely faster/best to simply try and fetch the row to begin with!