Wednesday, 12 August 2015

Avoid using COUNT() in a query to check existance of record.


Avoid using COUNT() in a query to check existance of record.


COUNT() counts all matching values by doing a table scan.
In case of EXISTS,When it finds the first matching value, it returns TRUE and stops.


SELECT column1 FROM TableName WHERE 0 < (SELECT count(*) FROM TableName2 WHERE condition)
better solution would be:

SELECT column1 FROM TableName WHERE EXISTS (SELECT * FROM TableName2 WHERE condition)