IF EXIST Vs COUNT(*)
Many times we see that people use count(*) to get the condition that if we have any record like
IF (SELECT COUNT(*) FROM Employee where Salaried =0 ) >0
BEGIN
PRINT 'Yes Got It'
-- Do your calculation here.
END
We are doing some calculation if we get Salaried=0 for at least once. And I know many times we use the same trick.
"The cost for getting the count(*) is that it counts all the data we get by where clause."
Use if exist to reduce this overhead.
IF EXISTS(SELECT * FROM Employee where Salaried =0)
BEGIN
PRINT 'Yes Get it'
-- Do your calculation here.
END
In this as soon as we get the first record further execution stops and it comes out of the if condition with true. If this not get any result then will cost same as above query.
No comments:
Post a Comment