117

Say I have an ID row (int) in a database set as the primary key. If I query off the ID often do I also need to index it? Or does it being a primary key mean it's already indexed?

Reason I ask is because in MS SQL Server I can create an index on this ID, which as I stated is my primary key.

Edit: an additional question - will it do any harm to additionally index the primary key?

11 Answers 11

80

You are right, it's confusing that SQL Server allows you to create duplicate indexes on the same field(s). But the fact that you can create another doesn't indicate that the PK index doesn't also already exist.

The additional index does no good, but the only harm (very small) is the additional file size and row-creation overhead.

1
  • 45
    The damage of unused indexes are very harmful indeed. For one thing, indexes eat up storage. For another thing, it slows down writes and updates. Always delete indexes that are not going to be used.
    – Pacerier
    Jul 6, 2012 at 7:40
61

As everyone else have already said, primary keys are automatically indexed.

Creating more indexes on the primary key column only makes sense when you need to optimize a query that uses the primary key and some other specific columns. By creating another index on the primary key column and including some other columns with it, you may reach the desired optimization for a query.

For example you have a table with many columns but you are only querying ID, Name and Address columns. Taking ID as the primary key, we can create the following index that is built on ID but includes Name and Address columns.

CREATE NONCLUSTERED INDEX MyIndex
ON MyTable(ID)
INCLUDE (Name, Address)

So, when you use this query:

SELECT ID, Name, Address FROM MyTable WHERE ID > 1000

SQL Server will give you the result only using the index you've created and it'll not read anything from the actual table.

2
  • This is of course a very old topic, but still equally current, so I'll ask: when the table has an existing clustered index, created on the primary key - are there any benefits on using an index as in this post? If we would not have such a nonclustered, covering index, the DB would actually use the clustered index to find the ID, and then "read" the needed columns' values from itself (since clustered index is per definition a covering one)? Is the only benefit the reading of the smaller index, so reading less data from the storage?
    – userfuser
    Feb 8, 2023 at 10:55
  • @userfuser - Yes, the purpose of the suggested method is to help the DB server read less data from the storage. It makes sense when you have a huge table (from storage size perspective) with many columns, but you need to frequently query a handful of them
    – red.clover
    Feb 23, 2023 at 8:35
29

NOTE: This answer addresses enterprise-class development in-the-large.

This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.

In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.

Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.

The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.

I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.

4
  • What if the key is a int or bigint autoincrement key? Is SQL Server smart enough to not do a unique index scan in this case? May 9, 2013 at 22:16
  • 1
    @quillbreaker: an IDENTITY field is not guaranteed to be unique. After all, users can insert duplicate values if they user IDENTITY_INSERT.
    – user565869
    Mar 9, 2015 at 18:59
  • I know this is an ancient topic, but I don't understand how a uniqueness scan of one index would be such a load on the system. A B+tree scan should be O(log n) * v where v is constrained overhead for index fragmentation, imperfect tree balance, etc.. Thus 2 billion rows would be log base 2 of 2,000,000,000 (about 31 seeks) times, say, 2 or 3 or even 10. 40M inserts per day is about 462/sec, ~100 IO's per insert... Ahh... Oh. I see. And this was before widespread SSDs. Apr 20, 2017 at 22:32
  • Unless you dropped the uniqueness constraint, wouldn't the overhead of checking each of the rows for uniqueness be much greater? Nov 29, 2017 at 16:45
23

Primary keys are always indexed by default.

You can define a primary key in SQL Server 2012 by using SQL Server Management Studio or Transact-SQL. Creating a primary key automatically creates a corresponding unique, clustered or nonclustered index.

http://technet.microsoft.com/en-us/library/ms189039.aspx

9

Here the passage from the MSDN:

When you specify a PRIMARY KEY constraint for a table, the Database Engine enforces data uniqueness by creating a unique index for the primary key columns. This index also permits fast access to data when the primary key is used in queries. Therefore, the primary keys that are chosen must follow the rules for creating unique indexes.

8

a PK will become a clustered index unless you specify non clustered

7

Declaring a PRIMARY KEY or UNIQUE constraint causes SQL Server to automatically create an index.

An unique index can be created without matching a constraint, but a constraint (either primary key or unique) cannot exist without having a unique index.

From here, the creation of a constraint will:

  • cause an index with the same name to be created
  • deny dropping the created index as constraint is not allowed to exists without it

and at the same time dropping the constraint will drop the associated index.

So, is there actual difference between a PRIMARY KEY or UNIQUE INDEX:

  • NULL values are not allowed in PRIMARY KEY, but allowed in UNIQUE index; and like in set operators (UNION, EXCEPT, INTERSECT), here NULL = NULL which means that you can have only one value as two NULLs are find as duplicates of each other;
  • only one PRIMARY KEY may exists per table while 999 unique indexes can be created
  • when PRIMARY KEY constraint is created, it is created as clustered unless there is already a clustered index on the table or NONCLUSTERED is used in its definition; when UNIQUE index is created, it is created as NONCLUSTERED unless it is not specific to be CLUSTERED and such already does not exist;
2

Making it a primary key should also automatically create an index for it.

1

Well in SQL Server, generally, primary key is automatically indexed. This is true, but it not guaranteed of faster query. The primary key will give you excellent performance when there is only 1 field as primary key. But, when there are multiple field as primary key, then the index is based on those fields.

For example: Field A, B, C are the primary key, thus when you do query based on those 3 fields in your WHERE CLAUSE, the performance is good, BUT when you want to query with Only C field in the WHERE CLAUSE, you wont get good performance. Thus, to get your performance up and running, you will need to index C field manually.

Most of the time, you wont see the issue till you hits more than 1 million records.

0

I have a huge database with no (separate) index.

Any time I query by the primary key the results are, for all intensive purposes, instant.

1
  • That is because the PK is a clustered index, look at your query plan
    – SQLMenace
    Jan 20, 2009 at 18:31
0

primary keys are automatically indexed

you can create additional indices using the pk depending on your usage

  • index zip_code, id may be helpful if you often select by zip_code and id
1
  • this is the answer I Was looking for - "why I should create index?" Oct 27, 2020 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.