I have the following query:
SELECT COUNT(*)
FROM Address adr INNER JOIN
Audit a on adr.UniqueId = a.UniqueId
The query is taking quite long to complete. I feel dumb, but is there any way to optimize it? I want to count all the address entries that have an underlying auditable.
EDIT: all your inputs are much appreciated, here are some more details:
Since you have two sets of data, ordered by the same value.. have you tried a merge join instead of the nested loop join?
SET STATISTICS IO ON
SET STATISTICS TIME ON
SELECT COUNT(*)
FROM Address adr INNER JOIN
Auditable a on adr.UniqueId = a.UniqueId
OPTION (LOOP JOIN)
SELECT COUNT(*)
FROM Address adr INNER JOIN
Auditable a on adr.UniqueId = a.UniqueId
OPTION (MERGE JOIN)
SELECT COUNT(*)
FROM Address adr INNER JOIN
Auditable a on adr.UniqueId = a.UniqueId
OPTION (HASH JOIN)
Edit:
These explanations are conceptual. SQL Server may be doing more sophisticated operations than my examples show. This conceptual understanding, matched with the measuring of time and logical IO by the SET STATISTICS commands, and examination of query execution plans - form the basis of my query optimizing technique (grown over four years). May it serve you as well as it has me.
Setup
NestedLoop
The nested loop algorithm iterates the parent data set, and then searches the child data set once for each parent, making it cost: m * log(n)
Merge
The merge join algorithm iterates the parent data set once and the child data set once, making it cost: m + n. It relies on the data being ordered. If you ask for a merge join on un-ordered data, you will incur an ordering operation! This brings the cost to (m * log(m)) + (n * log(n)) + m + n. Even that might be better than nested loop in some cases.
Hash
The hash join algorithm iterates the parent data set once and the child data set once, making it cost: m + n. It relies on having a big enough card table to hold the entire contents of the parent data set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With