Example scenario: 1 employee will only have 1 address and 1 address will only own by that 1 employee. Below are 2 options, which are correct or neither both? More of my confusion is should I place Employee primary key into Address table or place Address primary key into Employee table?
I’m using PostgreSQL as some of you need to know which database am I using.
Option 1
Employee EmployeeId (PK) EmployeeName AddressId (FK) Address AddressId (PK) AddressLine1
Option 2
Employee EmployeeId (PK) EmployeeName Address AddressId (PK) AddressLine1 EmployeeId (FK)
Advertisement
Answer
Does an employee have an address, or, does an address have an employee?
I would say, an employee has an address. I would think of employees as having a primary key, and employee attributes.
employee table:
- employee id
- employee attributes
- …
Whether or not an address needs a primary key is another question. But, if you then want to give an employee an additional attribute, “address”, which resides in a separate table, I would first think of adding the foreign key in the address table to indicate to which employee this address belongs:
address table:
- employee id
- address attributes
- …
Note that now, an employee may have multiple addresses, but two employees cannot share the same address.
If you want multiple employees to share the same address, you could, for example, introduce a primary key in the address table, and use an intermediate table:
address table:
- address id
- address attributes
- …
employee_address table:
- employee id
- address id
In this case, both fields in the employee_address table are foreign keys. It would not make sense that these would be primary keys. Here, I think you would agree, the primary keys are in the employee and address tables.
To your original question then, I would naturally put the employee primary key into the address table, to show that an address belongs to an employee. But, it might not be as simple as that. You have to consider the use cases, such as whether or not two employees share the same address, and whether or not employees can have multiple addresses. Or, could employees not have an address, or, could an address not have any employees?