I’m writing a query and as I go along I’m analysing the SQL Profiler trace to monitor my query’s performance and speed.
While doing this I noticed that if I run 3 different selects on the same table, these are much faster than if I ran them grouped in one select with OR’s in the WHERE clause.
A)
SELECT * FROM navigation_trees nt INNER JOIN contents c ON c.navigation_tree_id = nt.id WHERE nt.id = @NodeID
SELECT * FROM navigation_trees nt INNER JOIN contents c ON c.navigation_tree_id = nt.id WHERE nt.id = @ParentID
SELECT * FROM navigation_trees nt INNER JOIN contents c ON c.navigation_tree_id = nt.id WHERE nt.id IN (SELECT id FROM @ChildrenIDS)
B)
SELECT * FROM navigation_trees nt INNER JOIN contents c ON c.navigation_tree_id = nt.id
WHERE
nt.id = @NodeID OR
nt.id = @ParentID OR
nt.id IN (SELECT id FROM @ChildrenIDS)
And here is the Profiler readings for the two queries:
CPU | Reads | Writes | Duration(ms)
A) 15 | 1095 | 0 | 26
B) 531 | 456139 | 0 | 541
Can you shed some light?
Many thanks.
Three selects are just three selects, A select with three conditions, joined by
ORare actually selects plus the additional cost of removing duplicates.If you’re sure that there will never be duplicates, consider using
UNION ALLrather thanOR. Or course, that’s a very general advice. When adjusting your queries only for the sake of performance, always refer to your execution plan to see that the specific piece of advice applies in your scenario.