While reading some SQL Tuning-related documentation, I found this:
SELECT COUNT(*)
:
I'm using this way:
IIF(EXISTS (SELECT TOP 1 1
FROM Users
WHERE FirstName = 'John'), 1, 0) AS DoesJohnExist
You can use:
SELECT COUNT(1) FROM MyTable WHERE ...
or
WHERE [NOT] EXISTS
( SELECT 1 FROM MyTable WHERE ... )
This will be more efficient than SELECT *
since you're simply selecting the value 1 for each row, rather than all the fields.
There's also a subtle difference between COUNT(*) and COUNT(column name):
COUNT(*)
will count all rows, including nullsCOUNT(column name)
will only count non null occurrences of column nameYou can use:
SELECT 1 FROM MyTable WHERE... LIMIT 1
Use select 1
to prevent the checking of unnecessary fields.
Use LIMIT 1
to prevent the checking of unnecessary rows.