I want to find out if I’ve got an empty set or not. In MS SQL I’d just use IF EXISTS and write a branch for either outcome, but I don’t have that luxury in MySQL. So, if I want to find out if a set is empty, which one of the following will be faster?
SELECT * FROM `table` WHERE (`table`.app_id = 455) LIMIT 1
vs
SELECT count(*) AS count_all FROM `table` WHERE (`table`.app_id = 455)
The answer here is the LIMIT is probably going to be faster, and the key lies in the WHERE clause.
If you run a count in MySQL on an indexed column, it is smart enough to use the cardinality of that column’s index to report to you the count. This makes the count method quite inexpensive when we truly want a count, without qualifications. As soon as we add that WHERE, we need to return every row that matches our criteria. The trick with LIMIT, though it is doing the same thing, is that it stops after it gets a match. Once that first row comes back, it’s done. On an indexed column, this shouldn’t be much of a difference at all, probably imperceptible to the user and certainly close enough even for a timing test…but on an unindexed column, stopping the table scan in the middle, or if you’re lucky enough, the beginning, would be an enormous time savings.
I may revisit this with some real numbers, but a friend of mine brought the question to my attention and I thought it was a really great one. I’m hoping to get some feedback.




0 comments ↓
There are no comments yet...Kick things off by filling out the form below.
You must log in to post a comment.