Which table to choose to hold foreign key reference

  • I am creating two tables employeePersonalDetails and employeeSalaryDetails in two different ways i.e., 1. employeeSalaryDetails maintains foreign key that references the primary key in employeePersonalDetails

    create table employeePersonalDetails

    (

    employeeId int,

    employeeName varchar(30),

    employeeAddress varchar(255),

    primary key (employeeId)

    );

    create table employeeSalaryDetails

    (

    employeeId int,

    employeeSalary int,

    primary key (employeeId),

    foreign key(employeeId) references employeePersonalDetails(employeeId)

    );

    2. employeePersonalDetails maintains foreign key that references the primary key in employeeSalaryDetails

    create table employeeSalaryDetails

    (

    employeeSalaryId int,

    employeeSalary int,

    primary key (employeeSalaryId),

    );

    create table employeePersonalDetails

    (

    employeeId int,

    employeeName varchar(30),

    employeeAddress varchar(255),

    employeeSalaryId int,

    primary key (employeeId),

    foreign key(employeeSalaryId) references employeeSalaryDetails(employeeSalaryId)

    );

    My question here is: what factors would influence the decision to choose one of these implementations?

  • I'm not crazy about either approach. I prefer what you've done in the first approach. An employee has one or more salaries, so the Employee table (Not sure I'd call it EmployeePersonalDetails and if I did, I'd name the primary key after that name, not EmployeeID, clarity is your best friend) is the parent table and the salary table is the child. The foreign key would then go on the Salary table.

    But...

    Having the Employee ID be the primary key on the salary table doesn't work. I'm assuming you want a salary table in order to store salary changes over time (otherwise, it'd just be a column in the Employee table). So, you can't just have it be EmployeeID. You need an additional column, SalaryEffectiveDate or something, to differentiate a given salary for a given employee.

    So, if you differentiate the primary key on the child table and make the relationship there the way you have it defined, option 1.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply