Primary Key versus Unique Constraint?

前端 未结 16 1925
轮回少年
轮回少年 2020-12-13 03:49

I\'m currently designing a brand new database. In school, we always learned to put a primary key in each table.

I read a lot of articles/discussions/newsgroups posts

16条回答
  •  心在旅途
    2020-12-13 04:27

    Unless the table is a temporary table to stage the data while you work on it, you always want to put a primary key on the table and here's why:

    1 - a unique constraint can allow nulls but a primary key never allows nulls. If you run a query with a join on columns with null values you eliminate those rows from the resulting data set because null is not equal to null. This is how even big companies can make accounting errors and have to restate their profits. Their queries didn't show certain rows that should have been included in the total because there were null values in some of the columns of their unique index. Shoulda used a primary key.

    2 - a unique index will automatically be placed on the primary key, so you don't have to create one.

    3 - most database engines will automatically put a clustered index on the primary key, making queries faster because the rows are stored contiguously in the data blocks. (This can be altered to place the clustered index on a different index if that would speed up the queries.) If a table doesn't have a clustered index, the rows won't be stored contiguously in the data blocks, making the queries slower because the read/write head has to travel all over the disk to pick up the data.

    4 - many front end development environments require a primary key in order to update the table or make deletions.

提交回复
热议问题