Re: EXISTS() optimization
Posted by:
Toa Sty
Date: August 04, 2006 04:45AM
Hi folks,
I'm not sure what the best way to do this is either, but if your column is indexed and you're using MyISAM, doing something like:
SELECT IF(COUNT(myCol)>0, TRUE, FALSE) as rowExists FROM myTable WHERE myCol = xxx;
should give you an explain plan which says: Type "Const" or "Ref" and "Using Index", which is usually pretty good, but I think it can be improved.
Using MAX/MIN on indexed MyISAM tables is much quicker than COUNT if you have a WHERE clause. If you used MAX/MIN your query might look like:
SELECT !ISNULL(MAX(myCol)) as rowExists FROM myTable WHERE myCol = xxx;
and the explain plan should look something like: "Select tables optimized away" or "No matching min/max row".
The MAX/MIN version has a cost of 0, whereas
SELECT IF(COUNT(myCol)>0, TRUE, FALSE) as rowExists FROM myTable WHERE myCol = xxx;
(type="ref" and extra="Using Index") has some cost associated with it which can be large or small depending (I guess) on how many rows match your where condition. (more rows to count == more cost..)
Note that this won't work correctly if you only have NULLs for the values you're looking at because IF(count) would return TRUE and !ISNULL would return FALSE, so be a bit careful if you go down the MAX/MIN route. I think you're safe if your col can't contain NULLs.
I'm sure someone will point out a better, more direct way of working out whether any rows exist in a table for particular criteria anyway.. :)
Cheers,
Toasty
Subject
Views
Written By
Posted
20168
June 07, 2006 10:00AM
6867
July 25, 2006 07:54AM
5848
July 25, 2006 01:13PM
Re: EXISTS() optimization
5487
August 04, 2006 04:45AM
Sorry, you can't reply to this topic. It has been closed.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion
of Oracle or any other party.