Foriegn key in sql

A foreign key is a field (or collection of fields) in a table that refers to the primary key in another table. It is used to establish a relationship between the two tables.

A foreign key is usually implemented as a column (or group of columns) in a database table, and it is used to reference the primary key of another table. For example, consider a database with two tables: customers and orders. The customers table might have a primary key field called customer_id, and the orders table might have a foreign key field called customer_id that refers to the customer_id field in the customers table. This establishes a relationship between the two tables, such that each order in the orders table is associated with a customer in the customers table.

Here is a visual representation of this relationship using a simple ER (Entity-Relationship) diagram:

  • — — — — — — -+
    | customers |
    + — — — — — — -+
    | customer_id |
    + — — — — — — -+
    |
    |
    |
    + — — — — — — -+
    | orders |
    + — — — — — — -+
    | order_id |
    | customer_id | ← foreign key
    + — — — — — — -+
  • In this example, the customer_id field in the orders table is a foreign key that references the customer_id field in the customers table.

Did you find this article valuable?

Support Rushikesh Blog's by becoming a sponsor. Any amount is appreciated!