If i use a ForeignKey in SQL, does it always have to use all the column of the table I reference from?
So eg.
Table1
subjectID
firstname
surname
email
Table2:
car
books
Foreignkey(SubjectID)
Can i only use one column as Foreignkey, or do I always have to get all the columns?
Thanks!
A foreign key has to reference a unique key, usually the primary key.
So, if the parent table has a single column in its primary key that is the only column you need to use in the foreign key. If the parent table has a compound primary key (i.e. several columns) then you need all of those columns in the child table.
This is one reason why people tend to avoid using compound primary keys in favour of surrogate keys and unique constraints.
Here is a worked example (using Oracle but it works the same across all flavours of RDBMS). First we create a parent table with a single column primary key and reference it from the child table.
Simple enough. But if we drop those keys and give T1 a compound primary keys things fall apart …
We need to add a matching second column to the child table and include it in the foreign key definition: