What is the difference between a primary key and a surrogate key?

后端 未结 6 1708
遇见更好的自我
遇见更好的自我 2021-02-01 01:26

I googled a lot, but I did not find the exact straight forward answer with an example.

Any example for this would be more helpful.

6条回答
  •  日久生厌
    2021-02-01 01:48

    A surrogate key is a made up value with the sole purpose of uniquely identifying a row. Usually, this is represented by an auto incrementing ID.

    Example code:

    CREATE TABLE Example
    (
        SurrogateKey INT IDENTITY(1,1) -- A surrogate key that increments automatically
    )
    

    A primary key is the identifying column or set of columns of a table. Can be surrogate key or any other unique combination of columns (for example a compound key). MUST be unique for any row and cannot be NULL.

    Example code:

    CREATE TABLE Example
    (
        PrimaryKey INT PRIMARY KEY -- A primary key is just an unique identifier
    )
    

提交回复
热议问题