Is ID column required in SQL?

前端 未结 8 1533
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 23:50

Traditionally I have always used an ID column in SQL (mostly mysql and postgresql).

However I am wondering if it is really necessary if the rest of the columns in ea

8条回答
  •  时光说笑
    2020-12-30 00:01

    Don't confuse the logical model with the implementation.

    The logical model shows a candidate key (all columns) which could makes your primary key.

    Great. However...

    In practice, having a multi column primary key has downsides: it's wide, not good when clustered etc. There is plenty of information out there and in the "related" questions list on the right

    So, you'd typically

    • add a surrogate key (ID column)
    • add a unique constraint to keep the other columns unique
    • the ID column will be the clustered key (can be only one per table)
    • You can make either key the primary key now

    The main exception is link or many-to-many tables that link 2 ID columns: a surrogate isn't needed (unless you have a braindead ORM)

    Edit, a link: "What should I choose for my primary key?"

    Edit2

    For many-many tables: SQL: Do you need an auto-incremental primary key for Many-Many tables?

提交回复
热议问题