42

I want to know if composite primary keys are bad practice and if not, in which scenarios is their use beneficial?

My question is based on this article

databases design mistakes

Note the part about composite primary keys:

Bad Practice No. 6: Composite Primary Keys

This is sort of a controversial point, since many database designers talk nowadays about using an integer ID auto-generated field as the primary key instead of a composite one defined by the combination of two or more fields. This is currently defined as the “best practice” and, personally, I tend to agree with it.

Image of a composite primary key

However, this is just a convention and, of course, DBEs allow the definition of composite primary keys, which many designers think are unavoidable. Therefore, as with redundancy, composite primary keys are a design decision.

Beware, though, if your table with a composite primary key is expected to have millions of rows, the index controlling the composite key can grow up to a point where CRUD operation performance is very degraded. In that case, it is a lot better to use a simple integer ID primary key whose index will be compact enough and establish the necessary DBE constraints to maintain uniqueness.

2
  • 8
    This isn't a "good" or "bad" practice. Every design decision must serve a purpose; if you can explain (to yourself and others) why you need a composite PK, you're good to go. Conversely, if you can explain why you don't need it, you're good to go as well. The article you link to does a very poor job explaining, in my view.
    – mustaccio
    Commented Oct 21, 2017 at 15:06
  • Read what John Eisbrenner has to say about them here! Also look what I say about the overloading of BIGINT - much easier all round!
    – Vérace
    Commented Oct 21, 2017 at 19:50

3 Answers 3

69

To say that the use of "Composite keys as PRIMARY KEY is bad practice" is utter nonsense!

Composite PRIMARY KEYs are often a very "good thing" and the only way to model natural situations that occur in everyday life! Having said that, there would also be many situations where using a composite PK would be cumbersome and unwieldy and therefore not an optimal choice.

Your question is: "if composite primary keys are bad practice... (answered) and if not, in which scenarios is their use beneficial?".

Below is an example of where composite keys represent a rational/beneficial choice as the PK (indeed the only rational one as I see it - in the fiddle here, there's an extra example of having grades also!

On the plus side for composite keys, think of the classic Databases-101 teaching example of students and courses and the many courses taken by many students!

Create tables course and student:

CREATE TABLE course
(
  course_id SERIAL,
  course_year SMALLINT NOT NULL,
  course_name VARCHAR (100) NOT NULL,
  CONSTRAINT course_pk PRIMARY KEY (course_id)
);


CREATE TABLE student
(
  student_id SERIAL,
  student_name VARCHAR (50),
  CONSTRAINT student_pk PRIMARY KEY (student_id)
);

I'll give you the example in the PostgreSQL dialect (and MySQL) - should work for any server with a bit of tweaking.

Now, you obviously want to keep track of which student is taking which course - so you have what's called a joining table (also called linking, bridging, many-to-many or m-to-n tables). They are also known as associative entities in more technical jargon!

1 course can have many students.
1 student can take many courses.

So, you create a joining table

CREATE TABLE registration
(
  cs_course_id INTEGER NOT NULL,
  cs_student_id INTEGER NOT NULL,

  -- now for FK constraints - have to ensure that the student
  -- actually exists, ditto for the course.

  CREATE CONSTRAINT cs_course_fk  FOREIGN KEY (cs_course_id)
    REFERENCES course  (course_id),
  CREATE CONSTRAINT cs_student_fk FOREIGN KEY (cs_student_id) 
    REFERENCES student (student_id)
);

Now, the only way to sensibly give the registration table a PRIMARY KEY is to make that KEY a combination of course and student. That way, you can't get:

  • a duplicate of student and course combination

  • a course can only have the same student enrolled once, and

  • a student can only enroll in the same course one time only

  • you also have a ready made search KEY on course per student - AKA a covering index,

  • it is trivial to find courses without students and students who are taking no courses!

    -- The db-fiddle example has the PK constraint folded into the CREATE TABLE -- It can be done either way. I prefer to have everything in the CREATE TABLE statement.


ALTER TABLE registration
ADD CONSTRAINT registration_pk 
PRIMARY KEY (cs_course_id, cs_student_id);

Now, you could, if you were finding that searches for student by course were slow, use a UNIQUE INDEX on (sc_student_id, sc_course_id).

ALTER TABLE registration 
ADD CONSTRAINT course_student_sc_uq  
UNIQUE (cs_student_id, cs_course_id);

There is no silver bullet for adding indexes - they will make INSERTs and UPDATEs slower, but at the great benefit of greatly decreasing SELECT times! It's up to the developer to decide to index given their knowledge and experience, but to say that composite PRIMARY KEYs are always bad is just plain wrong.

In the case of joining tables, they are usually the only PRIMARY KEY that make sense! Joining tables are also very frequently the only way of modelling what happens in business or nature or in virtually every sphere I can think of!

This PK is also of use as a covering index which can help speed up searches. In this case, it would be particularly useful if one were searching regularly on (course_id, student_id) which, one would imagine, can often be the case!

This is just a small example of where a composite PRIMARY KEY can be a very good idea, and the only sane way to model reality! Off the top of my head, I can think of many many more.

An example from my own work!

Consider a flight table containing a flight_id, a list of departure and arrival airports and the relevant times and then also a cabin_crew table with crew members!

The only sane way this can be modelled is to have a flight_crew table with the flight_id and the crew_id as attibutes and the only sane PRIMARY KEY is to use the composite key of the two fields!

5
  • I have a similar situation as the student courses example you mentioned, but with the composite primary key with 2 columns, I also have 3 more columns whose data I need to update based upon the combination of composite keys. How do I do that ? I searched but couldn't find proper example. Thanks
    – Vipulw
    Commented Jul 17, 2021 at 14:34
  • @Vipulw - sounds like a new question to me. You can refer back here - that might be helpful?
    – Vérace
    Commented Jul 18, 2021 at 10:48
  • 1
    @Vérace-getVACCINATEDNOW What a great answer! Could you please expand more on when a composite PRIMARY KEY is not optimal? E.g., imagine table registration (postgres) where there are many more columns than just the minimal = 2 (or 3, if you add the numeric PK) columns. We need to optimize SELECT using index on PK. Assume we can take a hit on INSERT, DELETE and UPDATE. Now that I am writing, I wonder: should I ask a new question instead? Or could your answer be a canonical one? Asking for a friend. :) Commented Dec 14, 2021 at 20:18
  • @Vérace Can you mention another good example of having primary composite keys, where it is not used for a many-to-many joining table? Commented Feb 8, 2023 at 21:25
  • 1
    Szia @IstvánBékési - I can't think offhand of a good example - normally a surrogate key suffices for non-joining tables! You might conceivably have a PK on, say, the two letter abbreviation for US states, but you could use a SMALLINT or even a TINYINT instead of an 8 byte INTEGER. Some possible exceptions are mentioned here.
    – Vérace
    Commented Feb 13, 2023 at 9:33
7

My half-educated take: a "primary key" doesn't have to be the only unique key used to look up data in the table, although data management tools will offer it as default selection. So for choosing whether to have a composite of two columns or a random (probably serial) generated number as the table key, you can have two different keys at once.

If data values include a suitable unique term that can represent the row, I'd rather declare that as "primary key", even if composite, than use a "synthetic" key. The synthetic key may perform better for technical reasons, but my own default choice is to designate and use the real term as primary key, unless you really need to go the other way to make your service work.

A Microsoft SQL Server has the distinct but related feature of the "clustered index" that controls the physical storage of data in index order, and also is used inside other indexes. By default, a primary key is created as a clustered index, but you can choose non-clustered instead, preferably after creating the clustered index. So you can have an integer identity generated column as clustered index, and, say, file name nvarchar(128 characters) as primary key. This may be better because the clustered index key is narrow, even if you store the file name as the foreign key term in other tables - although this example is a good case for also not doing that.

If your design involves importing tables of data that include an inconvenient primary key to identify related data, then you're pretty much stuck with that.

https://www.techopedia.com/definition/5547/primary-key describes an example of choosing whether to store data with a customer's social security number as the customer key in all the data tables, or to generate an arbitrary customer_id when you register them. Actually, this is a grave abuse of SSN, aside from whether it works or not; it is a personal and confidential data value.

So, an advantage of using a real-world fact as the key is that without joining back to the "Customer" table, you can retrieve information about them in other tables - but it's also a data security issue.

Also, you're in trouble if the SSN or other data key was recorded incorrectly, so you have the wrong value in 20 constrained tables instead of in "Customer" only. Whereas the synthetic customer_id has no external meaning so it can't be a wrong value.

6
  • 1
    I especially appreciate the observation that depending on customer data as a key, even known unique customer data (here, SSN), breaks down if that data ever needs to be corrected. Commented Feb 4, 2020 at 17:59
  • 1
    What you call a synthetic key is generally called a surroagate key. My own answer is about linking two tables which themselves have surrogate keys - there's absolutely no point in creating a further surrogate for this - see comments! (+1 for your answer BTW).
    – Vérace
    Commented Mar 13, 2021 at 14:00
  • Regarding the issue with needing to correct a natural key value, that's what ON UPDATE CASCADE is for. You correct the value in the primary key column, and the DBMS automatically propogates the change to all referencing foreign keys.
    – Hannah Vernon
    Commented Mar 14, 2021 at 16:31
  • Vérace, Wikipedia's article on a "surrogate key" has eight other names for it, the second being "synthetic key" ;-) (and I did not edit it!) Commented Mar 15, 2021 at 21:10
  • Determining benefits of choosing a table key includes abstract theory and practical implementation details. In Microsoft SQL Server, a nonclustered index is, to ignore a lot of options, another table whose columns are the columns used in the index, plus the clustered index key. The computer finds the data you want much more easily than in a table with all the columns. Your fine example of a relationship between students and courses ends up with two indexes; one mainly provides courses of one student at a time, the other finds students of one course - neither need be unique but it's handy, Commented Mar 15, 2021 at 21:23
1

To expand on the answer that @Vérace - Слава Україні gave. Composite keys are also needed when you want to go deeper than 2 levels. If we continue the example given, each course is likely to have assignments.

Create Table Assignment {
assignmentid int not null,
assignment title varchar(255) not null,
assignment details text null,
deadline datetime null,
constraint pk_assignment Primary Key (assignmentid)
}

However, this doesn't work without the context of courses, so we can add a course id to the table

Alter Table Assignment add courseid int not null

But now you want to be able to look at the student's submissions. This means that we need a table linked to Registration for the assignments.

CREATE TABLE student_assignment
(
  cs_course_id INTEGER NOT NULL,
  cs_student_id INTEGER NOT NULL,
  cs_assignment_id integer not null,
  grade varchar(32) null,
  assignment blob null,
  submittedtime datetime null,
  Constraint pk_student_assignment primary key (cs_course_id, cs_student_id, cs_assignment_id)
}

As you can see, the natural key of this table is all three columns. You could possibly get it down to two columns by just using the assignment id and the student id, due to the fact that the course id already exists in the assignment table. However, doing that makes it harder to make reports that make sense. E.g. How many students submitted late work for a course, what the distribution of grades were, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.