Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server indexes - what columns to include in index?

Tags:

sql-server

Q1: Is it worthwhile to create indexes for foreign key columns in a SQL Server database?

Q2: If I have two related tables in a SQL Server database and I want to create an index on the foreign key column to improve performance, which columns do I need to include in the index and what type of index is best suited?

For example...

Table1

Table1ID int (Primary Key)

Table2

Table2ID int (Primary key)
Table1ID int (Foreign key)

..Would I create an Index for Table2 just with Table1ID or do I need to include the primary key (Table2ID) as well.

Q3: If I extend the example to include a third table which is related to both Table1 and Table2, do I create one index for each column or one index with both columns?

Table3

Table3ID int (Primary key)
Table1ID int (Foreign key)
Table2ID int (Foreign key)

like image 737
johna Avatar asked May 10 '12 23:05

johna


People also ask

Which columns should be indexed in SQL?

Primary key columns are typically great for indexing because they are unique and are often used to lookup rows.

What is included columns in indexes SQL Server?

Included columns can be used to create a covering indexes without including all the data into the key columns. This covering index has the advantage that the index contains all the columns that are needed for a query.

How do I choose which columns to index?

Columns with one or more of the following characteristics are good candidates for indexing: Values are unique in the column, or there are few duplicates. There is a wide range of values (good for regular indexes). There is a small range of values (good for bitmap indexes).


1 Answers

Q1. Yes. (You can always remove them later if you find they are not being used regularly).

Q2. Would I create an Index for Table2 just with Table1ID? Yes. Assuming the primary intended use of the index is to help the optimiser with joins between these 2 tables. (Rather than satisfy some other query that is part of your overall query workload).

Q3. Yes. Each column with a foreign key should have a separate index to its its parent key table.

(All assuming you have an OLTP database rather than an OLAP database)

This post provides TSQL that will generate a script of all the missing Foreign key indexes in a database: TSQL: Generate Missing Foreign Key Indexes

like image 144
Mitch Wheat Avatar answered Oct 23 '22 04:10

Mitch Wheat