Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Aptitude
  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • DBMS
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Algorithms
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture
Open In App
Next Article:
Foreign Key in DBMS
Next article icon

Foreign Key in DBMS

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A foreign key is distinct from other types of keys such as super keys, candidate keys, or primary keys because its primary purpose is to establish a connection between two tables in a database. It serves as a bridge, enabling relationships and ensuring data integrity by linking the records in one table to the relevant records in another.

Foreign Key

Foreign keys are a set of constraints in DBMS that establish relationships between tables and also ensure consistency and integrity of data. A foreign key is applied to a column of one table which references the primary key of a column in another table. It act as a cross-reference between two tables. It helps to maintain data integrity which is known as "Referential Integrity Constraints".

  • Note that it is essential that the referenced column in the other table must have a primary key (or at least a unique constraint). This is because the foreign key is used to link data between two tables, creating a relational structure that ensures data consistency and integrity.
  • A foreign key enforces referential integrity, which ensures that the data in one table corresponds to valid entries in another table. This prevents issues such as orphaned records, where a record in the referencing table points to a non-existent record in the referenced table.
  • To create a foreign key, we define the relationship between the columns during the table's structure creation. This is done by using the REFERENCES keyword, which specifies that a particular column will reference another column in a different table. The referenced column is typically the primary key of the related table, ensuring uniqueness and enabling the foreign key relationship.
  • A foreign key can refer to a column in the same table, which is called self-referencing. This is often used to show relationships within the same table, like a manager and their employees, members of a family tree, or folders inside other folders. It helps organize data in a way that shows how the rows in the table are connected to each other.

Example

foreign_key
Foreign Key Example
  • dept_id is primary key in department_info table.
  • dept_id is foreign key in employee_info table.

It means that dept_id field of employee_info table can have only those value which are present in dept_id field of department_info table.

  • dept_id field in department_info table is for unique identification of the records in the table.
  • dept_id field in employee_info table is for knowing which employee is working on which department.

Importance of Foreign Keys

Foreign keys are essential in databases for several reasons:

  • Streamline Data: Foreign keys prevent repeated data across multiple tables. They allow tables to share information without creating duplicate data, acting as a link between related tables.
  • Improve Efficiency: By working with primary keys, foreign keys create a clear structure in relational databases, making it faster to sort, search, and query data.
  • Maintain Data Accuracy: Foreign keys ensure data integrity by requiring that values in the foreign key column match existing values in the primary table. This ensures data stays accurate, even when changes or deletions occur in the primary table.

Syntax For Creating and Deleting Foreign Key

Let’s see the Foreign Key syntax used for creating a table.

Syntax for Creating Foreign Key:

CREATE TABLE Child_table_name (

Child_Column1 data_type,

Child_Column2 data_type, ...,

FOREIGN KEY (Child_foreign_key_column)

REFERENCES referenced_table_name (referenced_primary_key_column) );

Below syntax is used to delete the foreign key in DBMS.

Syntax for Dropping Foreign Key:

ALTER TABLE Child_table_name

DROP FOREIGN KEY Child_foreign_key_name;

Need of Foreign Keys in DBMS

Foreign keys plays a major role in database management systems (DBMS) for the following reasons:

  • Data Integrity: We need foreign keys as they help us making sure that data is consistent, complete, between both the tables and overall accuracy is maintained.
  • Query Optimization: Foreign keys optimizes the query execution by utilizing query plans more efficiently and improving the relationships between tables. It also helps in fast data retrieval.
  • Establishing Relationships: The main requirement of foreign keys is the establishment of relationships between tables. It makes sure that data is linked across multiple tables and helps in storing and retrieving data.
  • Data Security: Foreign keys helps in improving the security of data by preventing unauthorized modifications or deletions of important data in the referenced table.
  • Database Maintenance: Foreign keys are required in database maintenance tasks and help to ensure integrity and consistency of data during these operations.

Difference Between Primary Key and Foreign Key

  • Definition:
    • A primary key uniquely identifies each record in a table.
    • A foreign key links two tables by referencing the primary key of another table.
  • Purpose:
    • A primary key ensures each row in the table is unique.
    • A foreign key establishes relationships between tables and enforces referential integrity.
  • Uniqueness:
    • A primary key must be unique for each record and cannot contain null values.
    • A foreign key can have duplicate values and may allow null values, depending on the relationship.
  • Location:
    • A primary key is defined within the table it belongs to.
    • A foreign key is defined in one table but references the primary key of another table.
  • Example:
    • Primary Key: user_id in a Users table.
    • Foreign Key: user_id in an Orders table, linking to Users.user_id.

Read more about Difference Between Primary Key and Foreign Key.

To Read more about SQL FOREIGN KEY Constraint Refer, Here.

Conclusion

In this article we have learned about foreign key in DBMS. To summarize the article, a foreign key establishes relationship between tables and ensures consistency and integrity of data . It is applied to a column of one table which references the primary key of a column in another table. It is mandatory that the other column must have a primary key as it references the data which is related in different tables and creates a relational structure. Foreign key enforces referential integrity and makes sure that data is referenced from one table to table. In order to create a Foreign key we will specify the relationship between the columns during the creation of table's structure .


Next Article
Foreign Key in DBMS

A

adityajoh8d3r
Improve
Article Tags :
  • DBMS

Similar Reads

    Foreign Key in MariaDB
    MariaDB is an open-source database system which is similar to MySQL. It provide various features such as high availability and vertical scalability to allow database to scale up over various nodes or single node as features like Galera Cluster in MariaDB. The Foreign keys are the most important feat
    6 min read
    Joins in DBMS
    A join is an operation that combines the rows of two or more tables based on related columns. This operation is used for retrieving the data from multiple tables simultaneously using common columns of tables. In this article, we are going to discuss every point about joins.What is Join?Join is an op
    6 min read
    Entity in DBMS
    Database management systems (DBMS) are large, integrated collections of data, helping agencies keep, retrieve, and manage data effectively. At the core of any DBMS is the concept of entities, which is a basic concept that refers to real-world devices or ideas inside a database.EntityAn entity is a "
    4 min read
    Foreign key in MS SQL Server
    A foreign key in SQL Server plays a crucial role in establishing and enforcing relationships between tables. It is a column or a set of columns in a table that references the primary key or a unique key in another table. By using foreign key constraints the SQL Server keeps data consistent between r
    6 min read
    PL/SQL Foreign Key
    Maintaining data integrity is essential in relational database management systems. One essential concept in ensuring data consistency is the use of foreign keys. In PL/SQL, a foreign key creates relationships between tables, ensuring that the data in one table corresponds to the data in another. Thi
    7 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