In the relational databases, a foreign key is a field or a column that is used to establish a link between two tables.
A foreign key constraint. Returns the referenced columns if the foreignkey does not refer to the primary key. String The prefix to use in generated.
In simple words you can say that, a foreign key in one table used to point primary key in another table. Generated value auto increment non primary keys.
Let us take an example to explain it:
Here are two tables first one is students table and second is orders table.
Here orders are given by students.
First table:
S_Id | LastName | FirstName | CITY |
---|---|---|---|
1 | MAURYA | AJEET | ALLAHABAD |
2 | JAISWAL | RATAN | GHAZIABAD |
3 | ARORA | SAUMYA | MODINAGAR |
Second table:
O_Id | OrderNo | S_Id |
---|---|---|
1 | 99586465 | 2 |
2 | 78466588 | 2 |
3 | 22354846 | 3 |
4 | 57698656 | 1 |
Here you see that 'S_Id' column in the 'Orders' table points to the 'S_Id' column in 'Students' table.
The foreign key constraint is generally prevents action that destroy links between tables.
It also prevents invalid data to enter in foreign key column.
(Defining a foreign key constraint on single column)
To create a foreign key on the 'S_Id' column when the 'Orders' table is created:
MySQL:
SQL Server /Oracle / MS Access:
If the Order table is already created and you want to create a FOREIGN KEY constraint on the 'S_Id' column, you should write the following syntax:
Defining a foreign key constraint on single column:
MySQL / SQL Server / Oracle / MS Access:
If you want to drop a FOREIGN KEY constraint, use the following syntax:
MySQL:
SQL Server / Oracle / MS Access:
These are some important difference between primary key and foreign key in SQL-
Primary key cannot be null on the other hand foreign key can be null.
Primary key is always unique while foreign key can be duplicated.
Primary key uniquely identify a record in a table while foreign key is a field in a table that is primary key in another table.
There is only one primary key in the table on the other hand we can have more than one foreign key in the table.
By default primary key adds a clustered index on the other hand foreign key does not automatically create an index, clustered or non-clustered. You must manually create an index for foreign key.