Advantages and disadvantages of having composite primary key

前端 未结 3 1100
半阙折子戏
半阙折子戏 2021-02-05 23:20

Instead of having a composite primary key (this table maintains the relationship between the two tables which represents two entities [two tables]), the design is proposed to ha

3条回答
  •  醉话见心
    2021-02-05 23:58

    Cons:

    • Composite primary keys have to be imported in all referencing tables. That means larger indexes, and more code to write (e.g. the joins, the updates). If you are systematic about using composite primary keys, it can become very cumbersome.
    • You can't update a part of the primary key. E.g. if you use university_id, student_id as primary key in a table of university students, and one student changes university, you have to delete and recreate the record.

    Pros:

    • Composite primary keys allow to enforce a common kind of constraint in a powerful and seemless way. Suppose you have a table UNIVERSITY, a table STUDENT, a table COURSE, and a table STUDENT_COURSE (which student follows which course). If it is a constraint that you always have to be a student of university A in order to follow a course of university A, then that constraint will be automatically validated if university_id is a part of the composite keys of both STUDENT and COURSE.

提交回复
热议问题