I have a table with around 19 columns which contains reasonable large amount of data and is primarily being queried to retrieve data using select statements based on different where clause. Since this table is primarily queried to get data, I thought about creating Non Clustered indexes based on the different where clauses getting used in the queries. Also, all the get queries returns all the columns in the table as part of the select list. Based on the information above, I have two questions for selecting the indexes:
-
let us assume that we have the following SPs which queries as:
where [col_a] = {value} and [col_b] = {value} [col_b] = {value} and [col_a] = {value} [col_a] = {value} and [col_c] = {value} and [col_d] = {value} [col_a] = {value} and [col_c] = {value}I have created the following Non Clustered indexes on the table as
[col_a] and [col_b] –> Would the first SP still use this index as the
orders are reversed[col_a] and [col_c] and [col_d] –> Would the last SP use this index
as the first two columns match with orderAlso, should we go ahead and try to define Non Clustered indexes based on the filter/join clauses for the get SPs on a table?
-
Since the select list in all the SPs return the entire list of columns, I added all the columns of the table as included columns in the Non Clustered indexes(covering index) to avoid bookmark lookups. Is this approach correct? What are the space implications in this case since we are storing all the table columns as part of the index definition?
Yes – if you specify both columns, and your index contains those two columns as the first two in its list of columns, then the index can be used, and the order is not important.
If you have an index
(col_a, col_b), it can be used if you specify:col_acol_aandcol_b(order is irrelevant)but it cannot be used for a query that specifies just
col_b(but notcol_a). In order to be considered for use, the n left-most columns (n >= 1) must be used/defined – in any order.Yes – as I mentioned above, if the n left-most columns are used, the index can be considered, so if your specify the first two of a total of three – you’re fine.
Word of warning: just because you specify the right columns doesn’t necessarily mean that index will actually be used in the end. The query optimizer will consider it for use – but it might still go another way if that’s more convenient / faster.