Is a Primary Key necessary in SQL Server?

前端 未结 10 1126
旧时难觅i
旧时难觅i 2020-12-05 03:58

This may be a pretty naive and stupid question, but I\'m going to ask it anyway

I have a table with several fields, none of which are unique, and a primary key, whic

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

    I would never have a table without a primary key. Suppose you ever need to remove a duplicate - how would you identify which one to remove and which to keep?

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

    Necessary? No. Used behind the scenes? Well, it's saved to disk and kept in the row cache, etc. Removing will slightly increase your performance (use a watch with millisecond precision to notice).

    But ... the next time someone needs to create references to this table, they will curse you. If they are brave, they will add a PK (and wait for a long time for the DB to create the column). If they are not brave or dumb, they will start creating references using the business key (i.e. the data columns) which will cause a maintenance nightmare.

    Conclusion: Since the cost of having a PK (even if it's not used ATM) is so small, let it be.

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

    If you are accessing them via non-key fields the performance probably will not change. However it might be nice to keep the PK for future enhancements or interfaces to these tables. Does your application only use this one table?

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

    As SQLMenace said, the clustered index is an important column for the physical layout of the table. In addition, having a clustered index, especially a well chosen one on a skinny column like an integer pk, actually increases insert performance.

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

    The primary key is behind the scenes a clustered index (by default unless generated as a non clustered index) and holds all the data for the table. If the PK is an identity column the inserts will happen sequentially and no page splits will occur.

    But if you don't access the id column at all then you probably want to add some indexes on the other columns. Also when you have a PK you can setup FK relationships

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

    A primary key is really a property of your domain model, and it uniquely identifies an instance of a domain object.

    Having a clustered index on a montonically increasing column (such as an identity column) will mean page splits will not occur, BUT insertions will unbalance the index over time and therefore rebuilding indexes needs to be done regulary (or when fragmentation reaches a certain threshold).

    I have to have a very good reason to create a table without a primary key.

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