HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Two primary keys but not a composite, what is this sort of relationship called?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thiscalledprimarywhatbutkeystwocompositesortnot

Problem

I am integrating employee/position data with another system.

The first system is HR. It has an Employee table and a Positions table. The second system tracks office space and tracks who the office belongs to. It uses one table [em] to store both employees and position data.

If an employee changes position then the position id changes. If the position becomes vacant and a new employee fills the position then employee id is changed.

Both position id and employee ID act like primary keys for this table. I am trying to figure out if there is a name for this type of relationship in a database terminology?

Solution

It's called a composite key.

It doesn't matter how you use a composite key. If two pieces of data uniquely identify a row, it's called a composite key. In fact, the use case you're defining is almost always the use case of a composite key.

They're usually natural keys (having both fields related to the data), rather than surrogate keys (having both fields independent and abstract from the data). A store location, and product ID is the canonical example of a natural composite key. You're just using employees.

If, by chance, you mean to ask if both inputs used in the composite key have a name when they have a UNIQUE property, then no.. You can do it, but even in your case it's a bit awkward right? I mean, what if one employee is managing two spaces?

CREATE TABLE em ( emid serial PRIMARY KEY, name text, position text );
CREATE TABLE space ( spaceid serial PRIMARY KEY, owner text );
CREATE TABLE em_space (
  emid    int REFERENCES em,
  spaceid int REFERENCES space,
  PRIMARY KEY (emid, spaceid)
);

Code Snippets

CREATE TABLE em ( emid serial PRIMARY KEY, name text, position text );
CREATE TABLE space ( spaceid serial PRIMARY KEY, owner text );
CREATE TABLE em_space (
  emid    int REFERENCES em,
  spaceid int REFERENCES space,
  PRIMARY KEY (emid, spaceid)
);

Context

StackExchange Database Administrators Q#174505, answer score: 2

Revisions (0)

No revisions yet.