I’m using SQL Server 2012. What is the difference between indexing a single non clustered non-key column and putting multiple columns and then indexing?
If I have table with
- EmployeeID
- DepartmentID
- LocationID
- Name
- Address
If I create a single index on
- EmployeeID
- DepartmentID
instead of just
- EmployeeID
What is the difference? I created EmployeeID, DepartmentID index, when I was searching any employee with DepartmentID = X, the SQL Management Studio Actual Execution Plan was suggesting that I create an index on DepartmentID even though the table had a non clustered index on EmployeeID, DeparmentID?
In Indexes, order matters. You want to have the biggest subset first, followed by subsequently smaller subsets thereafter. So chances are, you will be looking for employees who belong to a certain department more than you will be looking for departments of a specific employee. Said another way, there are likely more employees per department than there are departments per employee — or at the very least, the consequence of searching is likely to first group by departments.
So if you change your single index from
EmployeeID+DepartmentIDtoDepartmentID+EmployeeIDyou’ll likely see that suggestion go away.More reading: http://weblogs.sqlteam.com/joew/archive/2008/02/13/60510.aspx