Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a primary key automatically an index?

Tags:

If I run Profiler, then it suggests a lot of indexes like this one

CREATE CLUSTERED INDEX [_dta_index_Users_c_9_292912115__K1] ON [dbo].[Users]  (  [UserId] ASC )WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF,  ONLINE = OFF) ON [PRIMARY] 

UserId is the primary key of the table Users. Is this index better than the one already in the table:

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [PK_Users] PRIMARY KEY NONCLUSTERED  (  [UserId] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,  IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON,  ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] 
like image 896
Lieven Cardoen Avatar asked Mar 12 '10 17:03

Lieven Cardoen


People also ask

Is primary key always an index?

Yes a primary key is always an index. If you don't have any other clustered index on the table, then it's easy: a clustered index makes a table faster, for every operation.

Is a primary key a type of index?

The primary key is a special unique index. Only one primary key index can be defined in a table. The primary key is used to uniquely identify a record and is created using the keyword PRIMARY KEY. Indexes can cover multiple data columns, such as index like INDEX (columnA, columnB), which is a joint index.

Does primary key automatically create index SQL Server?

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


1 Answers

Yes a primary key is always an index.

If you don't have any other clustered index on the table, then it's easy: a clustered index makes a table faster, for every operation. YES! It does. See Kim Tripp's excellent The Clustered Index Debate continues for background info.

So really, every useful table (except for maybe staging tables for bulkload or another few rare cases) ought to have a clustered index. If you don't have one, it's quite obvious the DTA would recommend one, and put it on the Primary Key column(s) by default.

like image 157
marc_s Avatar answered Oct 19 '22 09:10

marc_s