Do indexes work with “IN” clause

前端 未结 6 2104
生来不讨喜
生来不讨喜 2020-12-14 14:34

If I have a query like:

Select EmployeeId 
From Employee 
Where EmployeeTypeId IN (1,2,3)

and I have an index on the EmployeeTypeId

6条回答
  •  轮回少年
    2020-12-14 15:10

    So there's the potential for an "IN" clause to run a table scan, but the optimizer will try and work out the best way to deal with it?

    Whether an index is used doesn't so much vary on the type of query as much of the type and distribution of data in the table(s), how up-to-date your table statistics are, and the actual datatype of the column.

    The other posters are correct that an index will be used over a table scan if:

    • The query won't access more than a certain percent of the rows indexed (say ~10% but should vary between DBMS's).
    • Alternatively, if there are a lot of rows, but relatively few unique values in the column, it also may be faster to do a table scan.

    The other variable that might not be that obvious is making sure that the datatypes of the values being compared are the same. In PostgreSQL, I don't think that indexes will be used if you're filtering on a float but your column is made up of ints. There are also some operators that don't support index use (again, in PostgreSQL, the ILIKE operator is like this).

    As noted though, always check the query analyser when in doubt and your DBMS's documentation is your friend.

提交回复
热议问题