Can anyone help me understand in the simplest way what FOREIGN KEY means, and how it is used in a SQL statement? I've been reading about it a long but I can't comprehend.
The easiest way (for me, at least) to understand Foreign Key (FK) is to first understand Primary Key (PK):
A Primary Key is the expression (one or more columns) that will always only one record from the table. For example: a checking account number.
A Foreign Key, then, is a value in a different table that refers to that PK. For example: I have a table that records deposits and checks against a specific account. The account number will appear multiple times in this table, since you'll have multiple deposits and checks. But the account number will always refer to one and only one record in your master Accounts table. Since it always refers to exactly one record in a different ("foreign" table, it is a Foreign Key. Robert Bradley
Sr. DBA, some big company
cheap prints and oil paintings:
A foreign Key is a field with is linked to a field in another table (usually a primary key). It helps with database normalisation and reduces repeating data.
Example
-------
Say I have a flat file table of students with the following structure.
ID Class Last First
-------------------------------------
1 1A Smith Tom
2 1A Ryan Mary
3 2A Kelly Brian
4 2A Smith Ann
we usually would split the above table into two tables Class Table
------------
ClassID Name
------- -----
1 1A
2 2A
3 3A
Student Table
------------
ID ClassID Last First
--- ---- ----- -----
1 1 Smith Tom
2 1 Ryan Mary
3 2 Kelly Brian
4 2 Smith Ann
ClassID which is the Primary Key in the Class Table[/b] is joined to the Students Table by ClassID which is a Foreign Key.
If you notice, now that we have split the file up, we don't have repeating data.(i.e. the class name is not repeated in each record).
Furthermore if I am entering a Class in the Students table, because it is a Foreign key it MUST be present in the Class table before I can enter it. (this is called "Referential Integrity"
I hope this helps with your understanding of "Foreign Keys"!
:->
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.