Database “key/ID” design ideas, Surrogate Key, Primary Key, etc

前端 未结 7 1867
北荒
北荒 2021-02-09 16:15

So I\'ve seen several mentions of a surrogate key lately, and I\'m not really sure what it is and how it differs from a primary key.

I always assumed that ID was my prim

7条回答
  •  滥情空心
    2021-02-09 16:41

    No, your ID can be both a surrogate key (which just means it's not "derived from application data", e.g. an artificial key), and it should be your primary key, too.

    The primary key is used to uniquely and safely identify any row in your table. It has to be stable, unique, and NOT NULL - an "artificial" ID usually has those properties.

    I would normally recommend against using "natural" or real data for primary keys - are not REALLY 150% sure it's NEVER going to change?? The Swiss equivalent of the SSN for instance changes each time a woman marries (or gets divorced) - hardly an ideal candidate. And it's not guaranteed to be unique, either......

    To spare yourself all that grief, just use a surrogate (artificial) ID that is system-defined, unique, and never changes and never has any application meaning (other than being your unique ID).

    Scott Ambler has a pretty good article here which has a "glossary" of all the various keys and what they mean - you'll find natural, surrogate, primary key and a few more.

提交回复
热议问题