Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the down sides of using a composite/compound primary key?

Tags:

sql

database

What are the down sides of using a composite/compound primary key?

like image 730
JKueck Avatar asked Sep 20 '08 06:09

JKueck


People also ask

Is it bad to have composite primary key?

There is no conclusion that composite primary keys are bad. The best practice is to have some column or columns that uniquely identify a row. But in some tables a single column is not enough by itself to uniquely identify a row. SQL (and the relational model) allows a composite primary key.

When would you use a composite primary key?

A Composite Primary Key is created by combining two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined, but it does not guarantee uniqueness when taken individually, or it can also be understood as a primary key created by combining two or more ...

Are composite keys slower?

Having that composite primary key slows down SELECT s a tiny bit, though the effect is pretty much negligible and not worth worrying about. Having those columns indexed at all slows down your INSERT s, and you certainly are doing enough INSERT s to worry about it.


2 Answers

  1. Could cause more problems for normalisation (2NF, "Note that when a 1NF table has no composite candidate keys (candidate keys consisting of more than one attribute), the table is automatically in 2NF")
  2. More unnecessary data duplication. If your composite key consists of 3 columns, you will need to create the same 3 columns in every table, where it is used as a foreign key.
  3. Generally avoidable with the help of surrogate keys (read about their advantages and disadvantages)
  4. I can imagine a good scenario for composite key -- in a table representing a N:N relation, like Students - Classes, and the key in the intermediate table will be (StudentID, ClassID). But if you need to store more information about each pair (like a history of all marks of a student in a class) then you'll probably introduce a surrogate key.
like image 110
Max Galkin Avatar answered Oct 14 '22 19:10

Max Galkin


There's nothing wrong with having a compound key per se, but a primary key should ideally be as small as possible (in terms of number of bytes required). If the primary key is long then this will cause non-clustered indexes to be bloated.

Bear in mind that the order of the columns in the primary key is important. The first column should be as selective as possible i.e. as 'unique' as possible. Searches on the first column will be able to seek, but searches just on the second column will have to scan, unless there is also a non-clustered index on the second column.

like image 44
Matt Howells Avatar answered Oct 14 '22 19:10

Matt Howells