Search code examples
sqlsql-server

SQL Server table - ( or likely any SQL table) Does not having a primary key impact performance?


I have a table where I haven't explicitly defined a primary key, it's not really required for functionality... however a coworker suggested I add a column as a unique primary key to improve performance as the database grows...

Can anyone explain how this improves performance?

There is no indexing being used (I know I could add indexes to improve performance, what's not clear is how a primary key would also improve performance.)

The specifics

The main table is a log of user activity, it has a auto incrementing column for each entry, so it's already unique, but it isn't set as a primary key

This log table references activity tables which detail the specific activity, referenced by that autoincrementing entry in the main table. So the value is only unique in the main log table, there could be 100 entries in an activity table that reference that value as an identifier (ie. for session 212 Niall did these 500 things).

As you might guess the bulk of data is in the activity tables.


Solution

  • As Kimberly Tripp (the Queen of Indexing) clearly shows in her excellent blog post, The Clustered Index Debate Continues..., having a clustered index on your SQL Server table is beneficial - for all operations - yes, even for inserts!

    To quote Kimberly:

    Inserts are faster in a clustered table (but only in the "right" clustered table) than compared to a heap. The primary problem here is that lookups in the IAM/PFS to determine the insert location in a heap are slower than in a clustered table (where insert location is known, defined by the clustered key). Inserts are faster when inserted into a table where order is defined (CL) and where that order is ever-increasing.

    Since your primary key will by default automatically create a clustered index on that column you define, I would argue that yes, having a primary (clustering) key on your SQL Server table - even a log table - does have positive performance effects.