View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
  1. Home
DBMS

DBMS Tutorial: Learn Database Management Basics

Learn the fundamentals of Database Management Systems (DBMS) with our comprehensive tutorial. Understand key concepts and practical applications. Start now!

  • 32
  • 8 Hours
right-top-arrow
14

Foreign Key in DBMS

Updated on 29/07/2024446 Views

Database management systems (DBMS) contain a foreign key that plays an important role to establish and manage connections between tables. By linking tables, foreign keys ensure that relationships remain accurate and meaningful across entities. Successful DBMS and designs rely on a comprehension of the role and characteristics of keys. This article provides an examination of a foreign key in DBMS, explores their definition, types of relationships, implementation and recommended approaches.

Overview

In DBMS, foreign keys play a role, in linking tables. They maintain data accuracy by making sure that the information, in one table column matches the primary key values in another table. This practice enhances the organization and reliability of the database.

What is a Foreign Key in DBMS?

A foreign key in DBMS is a field or a set of fields in a table that uniquely identifies a row or record in another table. The two tables have a direct connection—often referred to as a parent-child relationship.

When a foreign key is defined in a DBMS table, it refers to the primary key of another table, establishing a logical relationship. This reference is critical in ensuring that the data in one table's foreign key column matches the values in another table's primary key. Foreign keys help preserve referential integrity and stop inconsistent or orphaned records from being created in the database by abiding by this principle.

Importance of Foreign Key

Foreign keys are important in a DBMS as they ensure data integrity and consistency. They prevent orphan records, enforce business rules, and ensure referential integrity. Foreign keys are critical in ensuring the accuracy and coherence of data stored in a relational database. They establish and enforce meaningful relationships between tables through the use of primary keys.

Types of Foreign Key Relations

Foreign key in DBMS is categorized into types based on cardinality. This includes:

One-to-One Relation

In a one-to-one relation, each record in a table is linked with exactly one record in another table. This means that for every record in the first table, there exists only one matching record in the second table, and vice versa. One-to-one relationships are relatively rare in database design but are useful for partitioning a large table and isolating sensitive data into separate tables.

Many-to-One Relation

A many-to-one relation, or many-to-one mapping, is where multiple records in one table are associated with a single record in another table. This is common in relational databases and is used to represent hierarchical data structures. For example, in a database of employees and departments, multiple employees can belong to the same department, creating a many-to-one relationship.

One-to-Many Relation

A one-to-many relation signifies that a single record in one table is associated with different records in another. This is a prevalent and essential relationship type in database design. For instance, in a database of customers and their orders, one customer can place multiple orders, establishing a one-to-many relationship between the "Customers" and "Orders" tables.

Many-to-Many Relation

Multiple records in a table can be linked to multiple records in another table. This necessitates the use of a junction table to link the related records. An example of this is the association between students and courses in a university database, where each student can join multiple courses, and each course can have multiple students.

The junction table, or associative or linking table, resolves the many-to-many relationship by storing pairs of related primary keys from the associated tables.

-- Creating the "authors" tableCREATE TABLE authors (    author_id INT AUTO_INCREMENT PRIMARY KEY,    author_name VARCHAR(100));-- Creating the "books" table with a foreign key referencing the "authors" tableCREATE TABLE books (    book_id INT AUTO_INCREMENT PRIMARY KEY,    book_title VARCHAR(255),    author_id INT,    FOREIGN KEY (author_id) REFERENCES authors(author_id));

Implementing Foreign Key

The implementation of foreign keys involves defining the foreign key constraint in the table schema. For example:

Output

Difference between Primary Key and Foreign Key

Aspect

Primary Key

Foreign Key

Definition

A primary key uniquely identifies each record in a table.

A foreign key in DBMS establishes a link between two tables, referencing the primary key of another table.

Uniqueness

Values in the primary key column(s) must be unique and cannot contain null values.

Values in the foreign key column(s) do not necessarily have to be unique and can contain null values, unless specified as NOT NULL.

Purpose

Ensures data integrity, enforces entity integrity, and provides a means of uniquely identifying each record in a table.

Establishes and maintains relationships between tables, enforcing referential integrity by ensuring that the values of the foreign key column are in correspondance to the values in the primary key of another table.

Constraints

Can be used to define a unique constraint, ensuring that no duplicate values are entered in the primary key column(s).

It defines a referential integrity constraint, ensuring all the values present in the foreign key column(s) are in correspondance with the values in the primary key of another table.

Role

Serves as a unique identifier for each record in the table and is used to establish relationships with other tables.

Acts as a bridge between two related tables, ensuring the consistency and integrity of the data between them.

Best Practices while Using Foreign Key

Here are some suggested practices to follow when using the foreign key:

  • Use consistent naming.
  • Consider indexing foreign key columns for improved query performance.
  • Ensure the data type and length of the foreign key in DBMS match the referenced primary key.
  • Exercise caution with cascade delete actions to prevent unintended data loss.
  • Enforce referential integrity constraints for data consistency.
  • Clearly document foreign key in DBMS relationships and communicate them to all stakeholders.
  • Periodically review and update foreign key constraints.

Need for Foreign Key

The need for foreign keys in a relational database arises from the requirement to establish and maintain relationships between tables. Foreign keys help maintain data consistency and prevent orphaned records.

They link information in tables and make it easier to retrieve associated data through joins. This improves data accuracy and reliability. Moreover, foreign keys are essential to establish and reinforce business rules and constraints in the database schema. This enhances data quality and integrity.

For example, take a database for a library.

Table: Books (Parent)

Columns: ISBN (Primary Key), Title, Author

Table: Borrowers (Child)
Columns: BorrowerID (Primary Key), Name, PhoneNumber

Foreign Key: BookISBN (references the ISBN in the Books table)

Here, the Borrowers table has a foreign key "BookISBN" that references the primary key "ISBN" of the Books table. This establishes a connection, indicating which book a borrower has checked out.

Referential Actions

Referential actions are rules defined on foreign keys to maintain referential integrity in a relational database. They dictate what actions should occur in the child table when a referenced row in the parent table is updated or deleted. The common referential actions include:

Cascade

If a referenced row is updated or removed, the same happens to the corresponding rows in the child table. This action takes the most aggressive approach. When a referenced row in the parent table is updated or deleted, all corresponding rows in the child table that reference it are also updated or deleted accordingly.

For example, if a book is deleted (parent row deletion), It will delete all borrowings associated with that book (risky, as borrowing data might be valuable).

Set Null

If a referenced row is updated or deleted, the foreign key columns in the child table are set to NULL.This action prioritizes data preservation in the child table. If a referenced parent row is deleted or updated, the foreign key column(s) in the child table are simply set to NULL. This indicates that the child record is "orphaned" and no longer has a valid reference in the parent table.

For example, if a book is deleted (parent row deletion), It will set the BookISBN in the Borrowers table to NULL, indicating the borrower has an outstanding book but the specific book record is gone.

Set Default

If a referenced row is updated or deleted, the foreign key columns in the child table are set to their default values.Similar to Set Null, this action prioritizes child table data. However, instead of setting the foreign key to NULL, it sets it to a predefined default value. This value could be a special code indicating a missing parent or a generic value like "0".

For example, if a book is deleted (parent row deletion), It will set BookISBN to a default value like "0" to signify a missing book reference.

Restrict

Prevents the update or deletion of a referenced row if there are matching rows in the child table. This action acts as a safeguard. If a referenced parent row is about to be deleted or updated, and there are still child rows referencing it, the operation is blocked. This prevents situations where child records become "dangling" with no valid parent reference.

For example, if a book is deleted (parent row deletion), prevent deleting the book if there are outstanding borrowings referencing it (ensures data consistency).

Ensuring that the database stays consistent is important when making changes, to data and these referential actions play a role, in maintaining data integrity.

Wrapping Up

A foreign key in DBMS plays a vital role in the design and maintenance of data accuracy. It enables valuable connections between tables and ensures efficiency and reliability.

FAQs

What is an example of a foreign key in DBMS?

A common instance of a key, in a database management system (DBMS) is when a column named "author" in an "books" table is linked to the "book_id" column, in the "author_id" table.

What is foreign key and primary key?

A foreign key entails a column or a set of columns that creates a link between two tables, referencing the primary key of another table. A primary key, on the other hand, is a column or a set of columns that uniquely acknowledges every record within a table.

What is alternate key in DBMS?

An alternate key in DBMS is a candidate key that is not the primary key. It acts as a unique identifier for a record but is not chosen as the primary means of identification.

What is unique key and foreign key?

A unique key makes each value in a column or a set of columns unique, while a foreign key establishes and enforces a link between two tables to maintain referential integrity.

What is called foreign key?

A foreign key is a single column or a set of columns that builds a link between two tables, referencing the primary key of another table.

Why is it called a foreign key?

It is known as a foreign key because it refers to a primary key in another (foreign) table, thereby establishing a relationship between the two tables.

Where is foreign key?

A foreign key is typically found in a table that is referencing another table. It represents the linked relationship between the two tables.

Is foreign key a key?

Yes, a foreign key is a key in a relational database. It contains single or multiple columns that provide a link between data in two tables.

What is the symbol for foreign key? In entity-relationship diagrams, a foreign key is typically represented by a line connecting the foreign key column(s) to the primary key column(s) in another table.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .