A Composite Key in a Table

A composite key identifies a row through several columns together. Each individual column can repeat when the full combination must remain unique.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a pair of fields
  2. Choose the true uniqueness constraint
  3. Test uniqueness on the complete tuple
  4. Pass the whole key to references and lookups

Trace a pair of fields

A table of room bookings may use room ID and start slot as a key. Slot 3 can appear in two rooms, and room A can have several slots. The pair room A, slot 3 can occur once. See composite dictionary keys.

Choose the true uniqueness constraint

If bookings can span more than one slot, unique starts alone do not prevent overlaps. Model the additional interval rule separately.[1][2]

Test uniqueness on the complete tuple

A local order number may repeat across branches. A key of (branch_id, order_number) can allow both (A,5) and (B,5) while preventing a second (A,5). Reversing component order changes query conventions and can affect index behavior. See composite dictionary keys.

Insert (A,5) → accepted
Insert (B,5) → accepted
Insert (A,6) → accepted
Insert (A,5) again → rejected

Pass the whole key to references and lookups

Looking up order number five alone does not identify one branch. A dependent table can reference the full composite key. Test a known order and a pair made from valid components that do not occur together.

References

  1. PostgreSQL Global Development Group, Data Definition ↩
  2. PostgreSQL Global Development Group, SQL Language Tutorial ↩