Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Primary Key and Foreign Key in DBMS

Last Updated on November 1, 2023 by Ankit Kochar

In the world of relational databases, two fundamental concepts play a crucial role in ensuring data integrity and maintaining the relationships between tables: primary keys and foreign keys. While they may sound similar, these database keys serve distinct purposes and have unique characteristics that are essential to comprehend for effective database design and management. In this article, we will delve into the key difference between primary key and foreign key, shedding light on their roles, functionalities, and best practices for their implementation. Whether you’re a seasoned database administrator or just beginning your journey into database management, understanding these differences is vital for building robust, efficient databases. Also we will discuss what is primary key in DBMS, and what is foreign key in DBMS.

What is the Key?

In database management systems, a key is a specific attribute or set of attributes used to uniquely identify each record (also known as a tuple) in a table. A key plays a crucial role in organizing data in a relational database and establishing relationships between tables. There are several types of keys in a database, each serving a different purpose.
Keys play a vital role in relational databases by uniquely identifying records, establishing relationships between tables, and improving performance.

  • Primary key
  • Foreign key
  • Candidate key
  • Composite key

Primary Key:

A primary key is a key that is used to identify a unique record in a database table. It is a fundamental component of database management, providing a way to ensure the integrity of data by ensuring that each record has a unique identifier. The primary key is used to establish relationships between tables, and it is also used to enforce data integrity by preventing the insertion of duplicate records into the table.

For example, consider a database table of employees. Each employee record in the table would have several attributes, such as name, date of birth, and job title. To identify each employee record, you could use an employee ID number as the primary key. This ID number would be unique for each employee and would be used to identify the corresponding record in the table.

The primary key is usually stored as an integer, but it can also be stored as a string, such as an employee name or a combination of several fields. It is important to choose the primary key carefully, as the key will be used throughout the database, and changing it can have a significant impact on the database structure and the relationships between tables.

In simple words, the primary key is a crucial component of database management, providing a way to identify unique records and enforce data integrity. It is important to choose the primary key carefully and to understand the impact that changes to the key can have on the database.

Syntax of Primary Key:

CREATE TABLE 
(
Column1 datatype,
Column2 datatype,  PRIMARY KEY (Column-Name)
.
);

Foreign Key:

A foreign key is a field in a database table that is used to establish a relationship between two tables. It is a way to enforce referential integrity in a database, meaning that the data in one table must match the data in another table.

For example, we have two tables: "Customers" and "Orders". The "Customers" table contains information about each customer, including their unique customer ID. The "Orders" table contains information about each order, including the customer ID of the customer who placed the order. In this case, the customer ID in the "Orders" table is a foreign key that references the customer ID in the "Customers" table.

By using a foreign key, we ensure that every order in the "Orders" table is associated with a customer in the "Customers" table. If we try to insert an order with a customer ID that does not exist in the "Customers" table, the database will reject the insert and raise an error. This helps to prevent data inconsistencies and ensures that the data in the database is accurate and up-to-date.

In simple words, a foreign key is a field in a database table that is used to establish a relationship with another table and enforce referential integrity. By using foreign keys, we can ensure the accuracy and consistency of data in a database.

Syntax of Foreign key:

CREATE TABLE ( 
column1    datatype,
column2    datatype,  
constraint (name of constraint) 
FOREIGN KEY [column1, column2...] 
REFERENCES [primary key table name] (List of primary key table column) ...);

Use of Primary Key and Foreign Key:

These are the uses of Primary key and foreign key

Primary Key Uses:

  • Identifying unique records: The primary key ensures that each record in a table has a unique identifier.
  • Establishing relationships: The primary key is used to link records in one table to records in another table through foreign keys, forming relationships between tables.
  • Enforcing referential integrity: By linking tables through primary and foreign keys, referential integrity is maintained and ensures that data remains consistent across multiple tables.
  • Improving query performance: Primary keys can be used as the basis for indexing, allowing for faster data retrieval.
  • Constraining data: The primary key can be used to enforce constraints, such as ensuring that data entered into a table is unique

Foreign Key Uses:

  • Establish the relationship between two tables in a database.
  • Identify a unique record in one table with the related record in another table.
  • Ensure referential integrity and maintain data consistency.
  • Prevent data anomalies and maintain database structure.
  • Facilitate data retrieval and analysis through joins.

Difference between Primary Key and Foreign Key?

These are the main difference between primary key and foreign key:

Feature                   Primary key             Foreign Key
Purpose A primary key is used to uniquely identify each record in a table Foreign key is used to link or connect two tables together.
Uniqueness Primary key must have unique values Foreign key may have duplicate values.
Null values Primary key cannot have null values Foreign key may have null values.
Number of columns A primary key can be one or multiple columns A Foreign key must be one column.
Owning table Primary key is located in the table it identifies Foreign key is located in a different table from the one it identifies.
Relationship type Primary key defines the parent table in a relationship Foreign key defines the child table.
Cardinality Primary key defines one-to-many relationship Foreign key defines the many-to-one relationship.
Cascade options Primary key has no cascade options Foreign key has options for update and delete cascading.
Referential integrity Primary key does not enforce referential integrity Foreign key enforces referential integrity.
Indexing Primary key is automatically indexed Foreign key may or may not be indexed.

Conclusion
In conclusion, the primary key in DBMS and foreign key in DBMS are cornerstones of relational database design, each with a specific role to play. The primary key acts as a unique identifier for records within a table, ensuring data integrity and providing the foundation for relationships with other tables. On the other hand, foreign keys establish these relationships by referencing the primary key of another table, enforcing referential integrity and allowing for complex data retrieval.

While both keys are integral to a well-structured database, they serve different purposes and have distinct attributes. Understanding these differences is essential for designing and maintaining efficient, error-free databases. By correctly implementing primary and foreign keys, you can ensure data consistency, accuracy, and the seamless flow of information within your database system.

FAQs Related to Primary Key and Foreign Key

These are the FAQs on the primary key and foreign key:

1. Why do we use primary keys and foreign keys in databases?

We use primary keys and foreign keys to enforce data integrity and to establish relationships between tables.

2. What is the difference between a primary key and foreign key?

A primary key is a unique identifier for each record in a table, while a foreign key is a column in a table that refers to the primary key of another table. The primary key ensures data integrity in its own table, while the foreign key helps to enforce referential integrity between tables.
A foreign key is a column or set of columns in a database table that establishes a link or relationship between that table and another table. It references the primary key of another table, enforcing referential integrity and allowing for the creation of relationships between tables.

3. Can a primary key and a foreign key be the same?

In some cases, a primary key of one table can also serve as a foreign key in another table. This scenario often arises in situations where two tables are closely related, and a column in one table is used to establish relationships with another table.

4. What happens if a foreign key references a non-existent primary key value?

When a foreign key references a value that does not exist in the primary key of the referenced table, it violates referential integrity, and the database management system typically prevents such actions. This helps maintain data consistency and prevents orphaned records.

5. Are primary keys and foreign keys required for all database tables?

Primary keys are often recommended for all tables to ensure data uniqueness and integrity. However, foreign keys are not mandatory for all tables and are only used when establishing relationships between tables. Their presence depends on the specific requirements of your database design.

6. Can a table have multiple primary keys or foreign keys?

No, a table can have only one primary key, which consists of one or more columns. In contrast, a table can have multiple foreign keys, each referencing different tables, allowing for complex relationships within the database.

Leave a Reply

Your email address will not be published. Required fields are marked *