As you are not fetching columns from role
you'd better not include it in the FROM
clause at all. Use this:
SELECT *
FROM person
WHERE person.roleid IN (SELECT id FROM role WHERE id = @Roleid)
This way the optimizer sees only one table in the FROM
clause and can quickly figure out the cardinality of the resultset (that is the number of rows in the resultset is <= the number of rows in table person
).
When you throw two tables with a JOIN
the optimizer has to look in the ON
clause to figure out if these tables are equi-joined and whether unique indexes exist on the joined columns. If the predicate in the ON
clause is complicated one (multiple ANDs and ORs) or simply wrong (sometimes very wrong) the optimizer might choose sub-optimal join strategy.
Obviously this particular sample is very contrived, because you can filter persons
by roleid = @Roleid
directly (no join or sub-query) but the considerations above are valid if you had to filter on other columns in role
(@Rolename for instance).