forest8 said:
Can someone explain to me what is a foreign key? When should I use it? How
are they work in a database?
A foreign key is a field in one table that identifies a specific record in
another table. Usually, the foreign key field holds a value that is the
primary key of a record in the other table. Thus, the foreign key field
serves to link related records in the two tables.
For example, you might have a table of Customers and a table of Orders.
Every order must be for a particular customer. These tables might contain
fields like these:
Customers
----------------
CustomerID (primary key; uniquely identifies the customer)
CustomerName
CustomerAddress
Orders
-----------------
OrderID (primary key; uniquely identifies the order)
OrderDate
OrderTotal
ShipDate
CustomerID (foreign key; identifies the customer
who placed this order)
The foreign key field CustomerID in the Orders table relates each order to
the specific customer who placed the order.
In a query, joining two tables on the key field(s) that relate them allows
the query to extract all the relevant information from both tables.