For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:
The optimization process and recommendations:
- Avoid Calling Functions With Indexed Columns (query line: 17): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `Col5` is indexed, the index won’t be used as it’s wrapped with the function `LTrim`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
- Avoid Calling Functions With Indexed Columns (query line: 18): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `Col1` is indexed, the index won’t be used as it’s wrapped with the function `LTrim`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
- Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
CREATE INDEX table1_idx_col1 ON Table1 (Col1);
The optimized query:
SELECT
a.Col1,
IsNull(a.Col2,
'') Col2,
IsNull(a.Col3,
'') Col3,
IsNull(a.Col4,
'') Col4,
IsNull(a.Col5,
'') Col5,
IsNull(b.Col2,
'') bCol2
FROM
Table1 a
LEFT OUTER JOIN
Table2 b
ON LTrim(RTrim(IsNull(a.Col5,
''))) = LTrim(RTrim(IsNull(b.Col1,
'')))
ORDER BY
a.Col1