What do you mean by foreign key?

41 Views

What do you mean by foreign key?

SQL | Foreign Key

A foreign key is a key used to link two tables. 


A Primary key of a table is used as a foreign key for the other table. Primary key is a field which can uniquely identify each row of a table.

Consider the two tables as shown below:

"Persons" table:

    +----------+-----------+-----+
    | PersonID | Name      | AGE |
    +----------+-----------+-----+
    | 1        | Kamal     |  32 |
    | 2        | Roshan    |  25 |
    | 3        | Shyam     |  23 |
    +----------+-----------+-----+

"Orders" table:

    +----------+-------------+----------+
    | OrderID  | OrderNumber | PersonID |
    +----------+-------------+----------+
    | 1        | 77895       |  2       |
    | 2        | 24562       |  1       |
    | 3        | 42456       |  1       |
    | 4        | 22456       |  3       |
    | 5        | 44678       |  2       |
    +----------+-----------+------------+

Notice that above two table have a unique column name called "PersonID" which is use for making relationship between the two table.

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

Tags:-