Search code examples
sqloracleforeign-key-relationshipjunction-table

Junction/Bridge tables Oracle SQL


Just a quick question regarding Junction tables in Oracle SQL. I understand their functionality and their role in a 'many to many' relationship but what about a 'one to many' relationship? I have two tables, Employees and Positions. Each Employee can only hold one position, however each each position can have many employees. e.g. John Doe can only be a sales executive, however there are 4 sales executives in the company. This is how I have it coded so far:

CREATE TABLE Positions (
position_id NUMBER(2) NOT NULL,
position_name VARCHAR2(25) NOT NULL,
CONSTRAINT pk_position PRIMARY KEY(position_id)
);

CREATE TABLE Employee (
emp_id NUMBER(3) NOT NULL,
emp_name VARCHAR2(30) NOT NULL,
emp_position NUMBER(2) NOT NULL,
emp_salary NUMBER(5) NOT NULL,
CONSTRAINT pk_employee PRIMARY KEY(emp_id),
CONSTRAINT fk_emp_pos FOREIGN KEY (emp_position) 
REFERENCES Position(position_id)
);

CREATE TABLE pos_emp (
position_id NUMBER(2) NOT NULL,
emp_id NUMBER(3) NOT NULL,
CONSTRAINT pk_pos_emp PRIMARY KEY(position_id, emp_id)
);

Is this correct? Is there a need for:
a. The foreign key in the Employee table?
b. The junction table?

I want to enforce the one employee to one role relationship in the employee table while being able to have the one role to many employees relationship in the junction table.

Hope this makes sense


Solution

  • The relations you have set up is a Many-Many relation. So if you want a one to many. Then the most common way is to skip the pos_emp and have the foreign key directly in Employee. So that the table looks something like this:

    CREATE TABLE Employee (
    emp_id NUMBER(3) NOT NULL,
    emp_name VARCHAR2(30) NOT NULL,
    emp_position NUMBER(2) NOT NULL,
    emp_salary NUMBER(5) NOT NULL,
    position_id NUMBER(2) NOT NULL,
    ...
    

    EDIT

    I have my employee table set up like that in my code. Will having the Position_id in the Employee table as the foreign key be enough to enforce each position having many employees?

    If the position_id in the Employee do not allow nulls then you cannot add a Employee without a position. That means that if you are trying to insert a Employee without a position you will get an exception that the foreign relation is not satisfy.

    But you need to check it in code so that when you add a Employee the position_id has a value. So you do not send the insert to that database if it do not have a value. Because that is a unnecessarily database call.

    And another interesting point is what should happened if you remove a Employee? Should you remove the Employee related to that position? If the answer is yes. You might consider to have a cascade delete from the position table. Otherwise you might need a trigger for it.