Create Table with Multiple Foreign Keys in SQL



A foreign key is a field (or collection of fields) in one table that refers to the primary key in another table. The table containing the foreign key is called the child table, and the table containing the primary key is called the parent table.

A foreign key ensures that the value in the foreign key column must match a value in the primary key column of the referenced table, maintaining referential integrity between the two tables.

Characteristics of a Foreign Key

  • A foreign key creates a relationship between two tables.
  • It ensures that the values in the foreign key column must match values in the referenced primary key column.
  • A table can have more than one foreign key.
  • A foreign key can accept NULL values, meaning the record is not linked to any value in the parent table.

Syntax

Following is the syntax for FOREIGN KEY ?

FOREIGN KEY (column_name) REFERENCES 
parent_table(primary_key_column);

Example

Imagine a food delivery system with three tables:

  • Customers table ? Stores customer information.
  • Restaurants table ? Stores restaurant information.
  • Orders table ? Stores order details and references both the Customers and Restaurants tables.
Create Customers Table
CREATE TABLE Customers (customer_id INT PRIMARY KEY,name VARCHAR(50));
  • customer_id ? It is the primary key that uniquely identifies each customer.
Create Restaurants Table
CREATE TABLE Restaurants (restaurant_id INT PRIMARY KEY,name VARCHAR(50));
  • restaurant_id ? It is the primary key that uniquely identifies each restaurant.
Create Orders Table With Multiple Foreign Keys
CREATE TABLE Orders (
  order_id INT PRIMARY KEY, 
  customer_id INT, 
  restaurant_id INT, 
  order_date DATE, 
  FOREIGN KEY (customer_id) REFERENCES Customers(customer_id), 
  FOREIGN KEY (restaurant_id) REFERENCES Restaurants(restaurant_id)
);
  • order_id ? It is the primary key of the Orders table.
  • customer_id ? It is a foreign key referencing Customers(customer_id).
  • restaurant_id ? It is a foreign key referencing Restaurants(restaurant_id).
  • Both foreign keys ensure that orders are placed only by valid customers and from valid restaurants.
Updated on: 2025-03-17T12:27:33+05:30

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements