How to use a specific index in a SQL Server query?

Asked

Viewed 11,373 times

19

I have a non-standard table in SQL Server installed on my PC which is fed monthly by Integration Services (SSIS) from a report in an Excel spreadsheet. I mean, I’m keeping track of a certain report.

This table has several key fields. Depending on the query I want to do in this table, I want SQL Server to use a specific index.

For example, the table below has several identification fields.

+---------------+---------+-------+
| Campo         | Tipo    | Index |
+---------------+---------+-------+
| DataID        | date    |   *   |
| NumFolhaID    | int     |   *   |
| LotacaoID     | int     |   *   |
| LotacaoNome   | varchar |       |
| LotacaoZona   | varchar |       |
| FuncMatricID  | int     |   *   |
| FuncVincID    | varchar |   *   |
| FuncNome      | varchar |       |
| FuncCpf       | varchar |       |
| CargoCarreira | varchar |       |
| CargoNome     | varchar |       |
| FuncaoNome    | varchar |       |
| Remuneracao   | money   |       |
| DataAdm       | date    |       |
+---------------+---------+-------+

I created three indexes:

  • INDEX_FUNC - composed of the fields (FuncMatricID, FuncVincID, DataID) in this order;
  • INDEX_LOTA - composed of the fields (LotacaoID, DataID, FuncVincID) in this order;
  • INDEX_FOLH - composed of the fields (DataID, NumFolhaID) in this order;

When using a SELECT I would like to use a specific index for the query.

  • Sorry, I do not know if this is a particularity of SQL Server, but I could not understand exactly at what point you are in need of help.

  • It wasn’t very clear to me either...

  • When using a SELECT I would like to use a specific index in order to optimize the search. For, if the index is in the order of INDEX_FUNC, when I use a query that adds the total of the field Remuneracao for LotacaoID, the query simply becomes slow, as the fields are indexed by other fields that are not part of the query strategy.

  • Force a certain index is never good...

1 answer

17


You can run the query as below:

SELECT CAMPO
FROM TABELA WITH (INDEX(INDEX_LOTA))

And you can also add INDEX to a Join

SELECT CAMPO
FROM TABELA T WITH (INDEX(INDEX_LOTA))
INNER JOIN OUTRA_TABELA OT
WITH (INDEX(OUTRO_INDICE))
ON OT.ID = T.ID
  • Opa, I’m breaking my head here with mysql, I need to select several records without the script pass more than 1 time by the same username or ID, I’m using Index in the query but returns me 1 record only, I need every F5 it return me another different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.