Search code examples
sqldatabase-designidentification

Using two Id's is good idea?


Example of table:

------------------------------------
| Id | ItemId | Description | Price |
------------------------------------ 

A two Id's (Id and ItemId) are both unique and generated automatically. Difference between them is that first Id(Id) used as classic Id for in-table identification and the second Id (ItemId) used as item identification field and it's resistant to table cleanup (when performing classic Id's reset) and migration.

That's good idea or not? And why? Please explain.


Solution

  • It's very common practice to implement (at least) two keys per table: a surrogate key, typically used for referential integrity purposes (Id in your example) and a natural key - AKA domain key or business key - used as an identifier in the business domain (presumably ItemId in your example).

    It isn't universally a good idea to use surrogates. You should decide on a case by case basis the intended purpose and advantage of each key you want to implement. Don't assume one design pattern fits all. As a very general rule some good criteria for choosing and designing keys are the familiarity, simplicity and stability of the key attribute(s). Aside from that, business rules should determine what keys you need. Have as many keys as necessary to model the business domain accurately and maintain data integrity.

    On a point of terminology, don't use the word Id if you really mean key. Id is far too ambiguous and overloaded. In relational/SQL databases rows are identified by keys. Id is ok for column names but not the right way to describe a table design or ask this question.