sql primary key and index

后端 未结 11 1402
误落风尘
误落风尘 2020-12-04 11:36

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 in

相关标签:
11条回答
  • 2020-12-04 12:10

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

    0 讨论(0)
  • 2020-12-04 12:12

    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.

    0 讨论(0)
  • 2020-12-04 12:14

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

    0 讨论(0)
  • 2020-12-04 12:14

    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;
    0 讨论(0)
  • 2020-12-04 12:18

    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.

    0 讨论(0)
  • 2020-12-04 12:21

    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

    0 讨论(0)
提交回复
热议问题