I\'ve searched around stackoverflow but everybody asks to optimize queries they\'ve already done.
I want to know, the basic stuff on what to do, what to avoid when creat
In your WHERE clause, avoid using a column as an input to a function, as this can cause a full table scan instead of being able to use an index. The query optimizer on some platforms does a better job than others, but it's generally better to be safe. For instance, if you're looking for records from the past 30 days, do the data manipulation against the date you're comparing against, not against your column:
BAD
WHERE DATEADD(DAY, 30, [RecordDate]) > GETDATE()
This may cause a full table scan (depending on the query optimizer for your platform), even if [RecordDate]
is indexed, because DATEADD(DAY, 30, [RecordDate])
has to be evaluated to compare it against GETDATE()
. If you change it to:
BETTER
WHERE [RecordDate] > DATEADD(DAY, -30, GETDATE())
This will now always be able to use an index on [RecordDate]
regardless of how good the query plan optimizer is on your platform, because DATEADD(DAY, -30, GETDATE())
gets evaluated once and can then be used as a lookup in the index. The same principle applies to using a CASE
statement, UDF's, etc.