Under what condition we need to use composite keys in database

前端 未结 4 1665
慢半拍i
慢半拍i 2021-02-09 19:17

i have seen that we can have composite keys where the primary key is made up from combined primary keys of two tables.

Like persons and Books

person_id a         


        
4条回答
  •  一整个雨季
    2021-02-09 20:22

    Composite keys should never be considered in "new" applications. They were used in the past, by people who used to think that "business keys" are better than "surrogate keys".

    Edit: As asked by Chris, I'm expanding my answer.

    Let me start by stating that I understand this question as "Composite Primary Keys" vs. "Surrogate keys".

    Also, I concede that there is one use case where a composite key makes sense: in cross reference tables, also called "link tables". These are used in many-to-many tables and consists in only two fields, both foreign keys that form a primary key for the xref table. For instance, UserRole table would contain user_id and role_id, nothing else. There's no class representation in Java, for instance, for a table like this. This is usually a @ManyToMany, with a Collection in both sides.

    I shared my views on Natural keys vs. Surrogate keys in another answer ( Hibernate : Opinions in Composite PK vs Surrogate PK ) , and I believe that Composite keys shares some of the disadvantages of the Natural key, without bringing any real benefit.

    The problem with composite keys is that you'll need two values to uniquely identify a record. This becomes a problem once you start having tables which references records in this first table. The second table then needs two columns to be able to reference one record. And if this second table uses a composite key made up of a single value + the foreign key, you now have three columns to uniquely identify one record. And a third table would need these three extra columns just to reference one record in the second table. Really, this is a snow ball.

    Another disadvantage is that requirements do change. All the time. So, what seems to be a good composite key today is not a key at all tomorrow. That's why we have surrogate keys: to be future-proof.

    Composite keys are mainly used so that records in a table are unique based on a set of columns. For instance, if you have a Customers table, you may have a NationalId+Country as a unique value, meaning that two users cannot share the same SSN if their country is USA. But it's possible to have the same number for two records, if they are not in the same country. If you like composite keys, this would be a good candidate for it. But as I hinted earlier, you can use a surrogate key and apply a unique constraint. You'll have the benefits of a composite key plus the safety of a surrogate key.

提交回复
热议问题