Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an SQL table have multiple primary keys?

On my job (non programming job that takes advantage of some of my programming skills), I was asked to generate a report from our outsourced, custom made program's SQL database.

When looking at the tables I see that many of them have multiple fields assigned as PK, why is that? What advantage does that have over a serial, numeric id?

like image 250
Ziv Avatar asked May 01 '26 20:05

Ziv


2 Answers

Data integrity. A key means a uniqueness constraint that prevents duplicate data entering the database. Keys help ensure that facts in the database can be properly identified with the real-world objects or concepts that they are supposed to describe. In practice not everything can or should be identified by a single attribute in a single column.

Note: A key with more than one attribute is not multiple keys. It's still just one key (called a composite key).

like image 151
nvogel Avatar answered May 03 '26 10:05

nvogel


It is called a composite key. If order_no is primary key in table Order and in table Order_Item there is a unique sequence number within order assigned to each order item, i.e. all orders have items beginning with sequence number 1 then the primary key for Order_Item would be order_no, item_sequence_no.

Contrast this with a generated primary key for Order_Item: you would still need a unique index on order_no, item_sequence_no. If you think about the queries you might find that more rely on the composite key.

The business dependent and system generated keys are technically known as domain key and surrogate key respectively. c2 wiki has a good discussion on it.

like image 34
Miserable Variable Avatar answered May 03 '26 10:05

Miserable Variable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!