Issue
So, I’m looking at a stored procedure here, which has more than one line like the following pseudocode:
if(select count(*) > 0)
...
on tables having a unique id (or identifier, for making it more general).
Now, in terms of performance, is it more performant to change this clause
to
if(select count([uniqueId]) > 0)
...
where uniqueId is, e.g., an Idx
containing double values?
An example:
Consider a table like Idx (double) | Name (String) | Address (String)
Now the ‘Idx’ is a foreign key which I want to join in a stored procedure.
So, in terms of performance: what is better here?
if(select count(*) > 0)
...
or
if(select count(Idx) > 0)
...
? Or does the SQL Engine Change select count(*)
to select count(Idx)
internally, so we do not have to bother about this? Because at first sight, I’d say that select count(Idx)
would be more performant.
Solution
The two are slightly different. count(*)
counts rows. count([uniqueid])
counts the number of non-NULL values for uniqueid
. Because a unique constraint allows a NULL
value, SQL Server actually needs to read the column. This could add microseconds of time to a query, particularly if the page with the id
is not already in memory. This also gives SQL Server more opportunities to optimize count(*)
.
As @lad2025 writes in a comment, the performant solution is to use if (exists . . .
.
Answered By – Gordon Linoff
Answer Checked By – Cary Denson (BugsFixing Admin)