Answer the question
In order to leave comments, you need to log in
Why not use the entity ID as the primary key in the database?
The question arose when designing a database that stores some objects. Each of these objects (some device) has its own globally unique identifier (let's call it domain id), which is a string of length 40 characters, and this identifier contains a certain knowledge of the subject area.
Intuitively, I understand that when storing a set of these objects in a table, it is better to use a separate integer field as the primary key, but when discussing with a partner, arguments other than
1. the semantics of the primary key and domain id are different, do not confuse it,
2. the base will operate faster with integers keys and not strings (but this statement has not been tested) and
3. coccyx I smell this is a bad idea
I don't have.
Objects are created quite infrequently, they are requested quite often, identifiers are used in other services of this system and in other tables.
Colleagues, throw in arguments or refute my arguments (especially the third one).
Answer the question
In order to leave comments, you need to log in
Primary key should be the field that is the identifier used for the selection. What for to do as primary key the integer identifier if the line is identified and requested on domain id? Just an extra index. If you can make a choice by an integer, then of course it should be added and used instead of domain id.
It is necessary to separate the business attributes of an entity from the system ones, since it is permissible for business attributes to change the structure of the attribute itself, for example, due to changes in legislation.
The primary key must be unique. @Kerman's statement could be taken as true, but one more index does not interfere in any way if it is needed for business.
Comments @sebres very much take place. Many DBMSs are designed to work optimally with numeric fields of the integer type (although some of them allow you to use the so-called GUID as a key, namely the character type, if desired). I doubt that, for example, MySQL has an optimization when working with an integer type: just look at the representation of its integer data in a table - they are presented as text, and not converted to an 8 or 16 byte value. Accordingly, the server either conducts a character-by-character comparison itself, or preliminarily converts the value into a "true", machine int, which also affects the speed. Conclusion: you need to find out what is more productive to use for your DBMS.
Advantages of a surrogate key: If the primary key has a large length, then when forming links of secondary (foreign) keys in other tables, there is a need to replace it with something both compact and unique at the same time, all the more subject to automatic generation, and not stupidly copy a long structure.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question