Do indexes work with “IN” clause

前端 未结 6 2125
生来不讨喜
生来不讨喜 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 14:55

    @Mike: Thanks for the detailed analysis. There are definately some interesting points you make there. The example I posted is somewhat trivial but the basis of the question came from using NHibernate.

    With NHibernate, you can write a clause like this:

    int[] employeeIds = new int[]{1, 5, 23463, 32523};
    NHibernateSession.CreateCriteria(typeof(Employee))
    .Add(Restrictions.InG("EmployeeId",employeeIds))
    

    NHibernate then generates a query which looks like

    select * from employee where employeeid in (1, 5, 23463, 32523)
    

    So as you and others have pointed out, it looks like there are going to be times where an index will be used or a table scan will happen, but you can't really determine that until runtime.

提交回复
热议问题