Create a foreign key from two different tables

I have two tables in PostgreSQL:

create Table student (
 studentID integer primary key,
 studentname text

create Table courses (
 courseID text primary key,
 schoolname text

I want to create a third table schoolstudent that has a foreign key (studentID, schoolname) where studentID references the primary key of the student table and schoolname references the schoolname key in the courses table.

How can I create a foreign key from two different tables in PostgreSQL 9.4 or 9.5?


A FK constraint requires a UNIQUE or PK constraint on the target column(s), which schoolname obviously cannot provide. You need another table with unique rows per school:

  school_id serial PRIMARY KEY,
  schoolname text NOT NULL

 student_id serial PRIMARY KEY,
 studentname text

CREATE TABLE schoolstudent(
 school_id  int REFERENCES school,
 student_id int REFERENCES student,
 PRIMARY KEY (school_id, student_id)

 course_id text PRIMARY KEY,
 school_id int REFERENCES school

Using short syntax for foreign key constraints. Details in the manual.

If you really need schoolname in the schoolstudent table (I seriously doubt that, looks like a design error), you can just add it. To enforce referential integrity you can include it in the foreign key, but you need a (redundant) matching UNIQUE constraint on school(school_id, schoolname), too.

CREATE TABLE schoolstudent(
 school_id  int,
 student_id int REFERENCES student,
 schoolname text,
 PRIMARY KEY (school_id, student_id),
 CONSTRAINT schoolstudent_combo_fk FOREIGN KEY (school_id, schoolname)
    REFERENCES school (school_id, schoolname) ON UPDATE CASCADE

Using explicit syntax in this case. And I suggest to cascade updates.

Or if schoolname is actually guaranteed to be UNIQUE (again, my doubts) you can replace school_id completely and just use schoolname as PK and FK column. Long text columns are not very efficient for the purpose, though - if performance matters. And schoolnames change, which is not ideal for PK columns.

You still need a separate school table in any case.

you can set many to many relation only if both the fields are Unique(probably Primary Keys).if above condition is Fulfilled you can use

CREATE TABLE Schoolstudent(
   ID INT references     student(studentID),
   Schoolname CHAR(50)  references courses(Schoolname),


But schoolname in table courses should be unique or PK.

Need Your Help

Is casting free() argument to void * neccessary?

c malloc free

Is it neccessary to cast the value passed to free() to a void pointer in this code snippet?

@ElementCollection of Enum in Embeddable

java hibernate jpa enums

I'm trying to use an elementCollection in an embeddable but JPA2.0 seems to ignore it.