I have been profiling the SQL query NHibernate generates for the following snippets below. I would think code #1 would be more efficient, however, the generated SQL gives me doubts.
1) bool any = Query.Where(user => user.Id == 1).Any(); generates:
select
*
from
users
where exists
(select id
from users
where id = 1)
and rownum <= 1
2) bool any = Query.Where(user => user.Id == 1).Count() > 1; generates:
select
count(*)
from
users
where
id = 1
Which is more efficient? In the future, how would I determine this? I am using Oracle.
Assuming that
IDis the primary key (or at least unique), the second query may be slightly more efficient because it only needs to read the index on theIDcolumn of theUSERStable. The first query will need to the same work to read the index but then will have to fetch the corresponding data from the table. If you look at the two query plans, you should see that the first query does an extra read of the table.On the other hand, if you were searching on a column that did not have a unique index on it, the second query be less efficient because it potentially has to read multiple blocks from the index or to do a full scan of the table to get a count while the first query can stop processing once it finds the first matching row.