Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL Query to Create Table With a Primary Key
Next article icon

How to Create a Table With a Foreign Key in SQL?

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A foreign key is a column or a set of columns in one table that references the primary key of another table. Foreign keys are used to establish and enforce a link between the data in two tables, ensuring referential integrity in the relational database system.

In this article, we will explain how to create tables with foreign keys in SQL, with multiple examples and outputs, to help us understand the process.

Why Use Foreign Keys in SQL?

Foreign keys are essential for maintaining the relationship between tables and ensuring data consistency. They help enforce the referential integrity of the database, meaning that a record in one table must have a corresponding valid record in another table. This prevents the creation of "orphaned" records and ensures data accuracy across the database.

Syntax

CREATE TABLE TABLE_NAME(
    Column 1 datatype,
    Column 2 datatype,
    Column 3 datatype FOREIGN KEY REFERENCES Table_name(Column name),
    ..
    Column n )

Key Terms

  • Column1, Column2, Column3 represent the columns of the table.
  • FOREIGN KEY (ColumnName) specifies the column that will act as a foreign key.
  • REFERENCES ReferencedTable(ReferencedColumn) links the foreign key column to a primary key column in another table.

Example: Creating a Table with a Foreign Key

Let's assume we are managing a customer relationship database where each sale is linked to a specific customer. Here's how we can create a Customer table and a Sales table, with a foreign key in Sales referring to the Customer table.

Step 1: Create the Customer Table

In order to create the following table, we use the following command

CREATE TABLE Customer(
Customer_id int primary key,
Customer_name varchar(20),
Customer_Address varchar(20),
)

Step 2: Insert the values into the Customer Table

After creating the above table, we can use the following SQL INSERT INTO statement:

INSERT INTO Customer (Customer_id, Customer_name, Customer_address)
VALUES
(101, 'Geek 1', 'Chennai'),
(102, 'Geek 2', 'Delhi'),
(103, 'Geek 3', 'Bombay'),
(104, 'Geek 4', 'Pune'),
(105, 'Geek 5', 'Nashik');

Output

Customer_idCustomer_nameCustomer_Address
101Geek 1Chennai
102Geek 2Delhi
103Geek 3Bombay
104Geek 4Pune
105Geek 5Nashik

Step 3: Create the Sales Table with a Foreign Key

Now, create the Sales table, where Customer_id will be a foreign key referring to the Customer_id in the Customer table. We can create the table using the following command.

CREATE TABLE Sales (
Sale_id INT PRIMARY KEY,
Customer_id INT,
Item_id INT,
Payment_mode VARCHAR(20),
FOREIGN KEY (Customer_id) REFERENCES Customer(Customer_id)
);

Step 4: Insert the values into the Sales Table

After creating the above table, we can use the following SQL INSERT INTO statement:

INSERT INTO Sales (Customer_id, Item_id, Payment_Mode)
VALUES
(101, 1334151, 'COD'),
(101, 16652, 'Debit Card'),
(104, 1009, 'Paypal'),
(102, 14543, 'COD');

Step 3: Verify the Data and Foreign Key Relationship

To verify that the foreign key relationship works, use the DESCRIBE command:

DESCRIBE Sales;

Output

Customer_idItem_IdPayment_Mode
1011334151COD
10116652Debit Card
1041009Paypal
10214543COD

Explanation:

  • In the Sales table, the Customer_id column is a foreign key.
  • This foreign key references the Customer_id column in the Customer table, ensuring that each sale record corresponds to a valid customer in the Customer table.

Other Methods to Create a Table with Foreign Key in SQL

There can be different ways of using the FOREIGN KEY constraint depending on our preference or specific requirements to create a table with foreign key in SQL.

Method 1: FOREIGN KEY Constraint After Column Declaration

Here, we will first declare all the columns, and then use foreign key constraint on the desired column. Now in order to create the same sales table using customer table we can run the following command.

Query:

CREATE TABLE SALES(
Customer_id int,
Item_id int,
Payment_Mode varchar(20),
CONSTRAINT FK_Sales FOREIGN KEY
(Customer_id)REFERENCES Customer(Customer_id)
)

Output

Customer_idItem_IdPayment_Mode
1011334151COD
10116652Debit Card
1041009Paypal
10214543COD

Method 2: Create Table with Foreign Key consisting of Multiple Attributes 

Foreign key can consist more than two attributes. Below is the implementation of foreign key consisting of multiple attributes referring to multiple columns of another table.

Query:

 Customer_id INT PRIMARY KEY,
Item_id INT,
Payment_Mode varchar(20),
Payment_id INT,

CONSTRAINT customer_payment_id
FOREIGN KEY (customerId, paymentId)
REFERENCES Customer(customerId, paymentId)
);

Output

Customer_idCustomer_nameCustomer_AddressPayment_id
101Geek 1ChennaiP100
102Geek 2DelhiP200
103Geek 3BombayP300
Customer_idItem_IdPayment_ModePayment_id
1011334151CODP100
10116652Debit CardP200

Explanation:

The above examples show reference of foreign keys consisting of more than one attribute. The constraint customer_payment_id is a foreign key containing two columns Customer_id and Payment_id. These foreign key refers to the two columns of parent table Customer - Customer_id, Payment_id.

SQL FOREIGN KEY ON ALTER TABLE 

Foreign key can also be added in the existing table using the ALTER TABLE statement. The following method will illustrate the same.

Query:

ALTER TABLE Retailer
ADD FOREIGN KEY (Retailer_id)
REFERENCES Customer(Customer_id);

Output

Retailer_idOrder_Purchased
101Item1
102Item2
103Item3

Explanation:

  • Here the table Retailer is an existing table containing Retailer_id as an attribute. Now we are altering the same table using the ALTER TABLE clause in dbms.
  • The column name that serves as the foreign key will come after the ADD FOREIGN KEY clause. After the REFERENCE clause we need to specify the Primary key and the table that is being referred. 

DROP Foreign Key Constraint

To remove a foreign key from a table requires execution of  the correct SQL statement, which will be different for each database management system (DBMS). The following are some instances of well-known DBMS:

MYSQL

ALTER TABLE table_name
DROP FOREIGN KEY foreign_key_name;

PostgreSQL/ SQL Server 

ALTER TABLE table_name
DROP CONSTRAINT foreign_key_name;

Conclusion

Creating and managing foreign keys in SQL is important for maintaining referential integrity between related tables in a database. Whether we are creating a new table or altering an existing one, foreign keys ensure that the data remains consistent and that relationships between tables are well-defined.

By implementing foreign keys properly, we can ensure the integrity and consistency of our relational database while efficiently managing the relationships between our data. Whether we are using simple or composite foreign keys, it’s important to understand the core concepts and apply them to optimize our database design.


Next Article
SQL Query to Create Table With a Primary Key

M

magichat
Improve
Article Tags :
  • DBMS
  • SQL
  • Databases
  • DBMS-SQL

Similar Reads

  • How to Create a Table With Multiple Foreign Keys in SQL?
    When a non-prime attribute column in one table references the primary key and has the same column as the column of the table which is prime attribute is called a foreign key. It lays the relation between the two tables which majorly helps in the normalization of the tables. A table can have multiple
    2 min read
  • How to add a foreign key using ALTER in MySQL
    In this article, we will discuss the overview of foreign keys and will discuss how to add a foreign key using ALTER in MySQL step by step. Let's discuss it one by one. Foreign key : If an attribute is a primary key in one table but was not used as a primary key in another table then the attribute wh
    3 min read
  • SQL Query to Create Table With a Primary Key
    A primary key is essential in SQL databases to uniquely identify each row in a table. It ensures data integrity by containing only unique and non-NULL values. A table can have only one primary key, which can consist of a single column or multiple columns, called a composite key. In this article, we
    5 min read
  • How to Create a View on a TEMP Table in SQL?
    In SQL Server, TEMP tables are used to store data temporarily during the session in which they are created. These tables are especially useful for storing intermediate results or simplifying complex queries. In this article, We will learn about whether can we create a view on a TEMP table in SQL Ser
    4 min read
  • How to Delete a Foreign Key Constraint in SQL
    Foreign key constraints are important for maintaining referential integrity in a relational database as they define relationships between tables. However, there are times when we may need to identify which foreign key constraints reference a specific table in SQL Server. This could be necessary for
    4 min read
  • How to Create One Table From Another Table in SQL
    Creating a table based on the structure and data of an existing table is a common task in database management. This process allows us to replicate a table for backup, testing or data transformation purposes. SQL provides efficient methods to create one table from another while preserving the schema,
    3 min read
  • Creating a Temp Table with an Identity in SQL
    In SQL Server, temporary tables are used for holding intermediate results or performing operations during a session or stored procedure. One useful feature of tables is the ability to have an identity column that auto-increments values as rows are inserted. This is particularly useful for generating
    5 min read
  • How to Temporarily Disable a Foreign Key Constraint in MySQL?
    MySQL is a popular open-source relational database management system (RDBMS) that is uniquely used to construct expandable and high-productivity databases. MySQL, which was created by MySQL AB and later acquired by its current owner Oracle Corporation, was originally introduced in 1995. MySQL is rep
    4 min read
  • Truncate Tables with Dependent Foreign Key Constraints in SQL
    Truncating a table is a common database operation used to efficiently remove all table rows. Unlike the DELETE statement which logs individual row deletions, TRUNCATE operates at the table level and make it faster and less resource-intensive. However, when foreign key constraints are involved trunca
    4 min read
  • Foreign Key with a Null Value in MySQL
    In databases, foreign keys are like links connecting two tables. They make sure that data in one table matches data in another. But a common question is whether a foreign key can be NULL. In this article, We will explain what NULL values mean for foreign keys, how they work with the help of examples
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences