Handling Id Uniqueness With a Single Key or with a Composite Key
0
votes
1
answer
38
views
First off, I'm new to architecting a DB and I'm looking for help from people who are more experienced and are able to point out gotchas and issues that I might not see.
I'm building out a new DB schema and I'm weighing the benefits of using composite keys for uniqueness vs a single primary key.
Here is an example. An Owner owns things, Things have components, Components have descriptions.
### Approach 1 - Composite Key
One way I can architect this is by giving the owner an
### Approach 2 - Single Key
The other way I can architect this is by making the
### Approach 1 - Pros & Cons
Pro: I like approach 1 because it has the potential to take less space with smaller keys and because it's more contained. The number of owners in the system doesn't really matter, the
INT
id, OwnerId
, and then anything they own a SMALLINT
id, OwnedThingId. The result is that each owner has MAX(SMALLINT)
things they can own. The other result is that the OwnedThingId
's are repeated in the db. For example, the table would have many different OwnedThingId
's of 1
. Uniqueness is only attainable by composing the OwnedThingId
with the OwnerId
. In this case the PK would be (OwnerId
, OwnedThingId
).

OwnedThingId
bigger, say an INT
, and make that field unique throughout the whole table. In this case there would only be one thing with an id of 1
, regardless of how many owners there are. The result is that there is a limit of MAX(INT)
for **all owners**. However, the record is now easier to refer to since I only need an OwnedThingId
instead of both an OwnerId
and OwnedThingId
.

OwnedThingId
's available to the owners doesn't change. It also mirrors the real world a bit better. i.e. Student id 12 isn't the same student at all the schools ever.
Con: Since multiple ids are required to determine uniqueness, there is the potential for a future table to store and need to refer to X number of id's instead of just storing one id.
### Approach 2 - Pros & Cons
Pro: Only one field is needed to confer uniqueness. A Record is unique across all owners. There is also less to keep track of, a future table would only need to store and refer to the one unique id.
Con: It can take more space because it uses bigger int values. Each owner that claims an id, reduces the pool of available ids for all owners.
### Conclusion
Like I said, I'm leaning towards approach 1, but I get the feeling like I might be shooting myself in the foot as time goes on and the system grows. Thus I am reaching out to those with more experience in architecture than I to inform me of potential gotcha's or reasons why I should consider one over the other.
Asked by jeremysawesome
(121 rep)
Mar 27, 2024, 06:01 PM
Last activity: Mar 28, 2024, 04:49 AM
Last activity: Mar 28, 2024, 04:49 AM