Question

Say I have a typical customer table;

Id Int Identity Primary Key, 
FirstName varchar(255), 
LastName varchar(255), 
Phone VarChar(30)

So primary key creates a clustered unique index on Id.

To make searching faster, I want to add indexes to the name fields.

My question is whether I should add the Id to those indexes or will those indexes tie themselves to the primary key anyway.

For instance;

Create Index IX_Customer_FirstLastName On Customers(FirstName, LastName, Id)

... is that overkill?

Is the following more or less efficient?

Create Index IX_Customer_FirstLastName On Customers(FirstName, LastName)

TIA

Was it helpful?

Solution

It wouldn't make sense to add the ID to your other index. It would only be helpful if you had a large number of rows with identical firstName lastName combinations, and you already knew the ID...

But if you already knew the ID for the records that you're searching for, you could just search using your clustered index.

Additionally, every non-clustered index already contains a value for the clustered index so that it can look up the row using the clustered index after it has been found using the non-clustered index. You wouldn't have to include ID in your non-clustered index if you wanted to make it a covering index for the fields (FirstName, LastName, Id)

Final note, if you make a single index using FirstName and LastName, this index will only be used on searches that include the FirstName, the leading edge of your index. If you plan on performing searches using just LastName, or just FirstName, create two indexes, one for each column.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top