In an SQL database what is a foreign key and why you use it?
In the context of relational databases, a foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table or the same table. In simpler words, the foreign key is defined in a second table, but it refers to the primary key or a unique key in the first table.
This takes us to Primary key. The customers table contains a unique key on each row called customerNumber this is the primary key for the table. On the orders table we have the orderNumber column which is the primary key for that table.
The orders table has a foreign key link back to the customers table though the customer Number. We call the customer Number the foreign key.
Customer Table:
customerNumber CustomerName.
1 Bob
2 Jane
Order table:
OrderNumber customerNumber Status
1 1 Shipped
2 1 Exploded
Using the data above if you wanted to see what orders bob had you would take the primary key being bobs customer id and check the order table for all rows containing the it. This is the foreign key linking two tables.