I need to find a fast way to determine if records exist in a database table. The normal method of IF Exists (condition) is not fast enough for my needs. I've found something that is faster but does not work quite as intended.
The normal IF Exists (condition) which works but is too slow for my needs:
IF EXISTS (SELECT * From dbo.SecurityPriceHistory Where FortLabel = 'EP' and TradeTime >= '2020-03-20 15:03:53.000' and Price >= 2345.26) My work around that doesn't work, but is extremely fast:
IF EXISTS (SELECT IIF(COUNT(*) = 0, null, 1) From dbo.SecurityPriceHistory Where FortLabel = 'EP' and TradeTime >= '2020-03-20 15:03:53.000' and Price >= 2345.26) The issue with the second solution is that when the count(*) = 0, null is returned, but that causes IF EXISTS(null) to return true.
The second solution is fast because it doesn't read any data in the execution plan, while the first one does read data.
count(*)could be faster than theexistsquery -- Unless SQL Server is smart enough to know that an aggregation query with noGROUP BYorHAVINGalways returns one row, soEXISTSis always true.IIF()has nothing to do with it. It is theCOUNT(*)that returns one row.