I have a table ‘customertransactions’ with a column ‘transactiondate’ of type DateTime.
I will be querying it with the following:
SELECT SUM(balance) AS totalbal FROM customertransactions WHERE accountcode=?
AND (MONTH(GETDATE())-MONTH(transactiondate)+12*(YEAR(GETDATE())-YEAR(transactiondate)))>= 3
… obviously passing a sanitised parameter for ‘accountcode’.
My question is – how do I best create an index to optimise that ?
Thanks.
Primarily, I would consider indexing
accountcode. Additionally, if you can rewrite your date clause so that it is sargable, then you may benefit from indexingtransactiondateas well.As always, consider the cardinality of your data, and examine the query plan when adding indexes. There are no hard and fast rules.