Wednesday, 5 February 2025

Difference Between Primary Key and Foreign Key

comparison between Primary Key and Foreign Key:

Feature Primary Key Foreign Key
Definition Uniquely identifies a record in a table Establishes a relationship between two tables
Uniqueness Must be unique for each row Can have duplicate values
NULL Values Cannot be NULL Can have NULL values
Number of Keys in a Table Only one primary key per table A table can have multiple foreign keys
Relation Defines the main identifier for a record Refers to the primary key of another table
Dependency Independent, does not depend on any other table Always refers to a primary key in another table
Indexing Automatically indexed Not automatically indexed
Modification Cannot be modified once assigned Can be updated, but should match a valid primary key
Example In Employees table: Emp_ID (Primary Key) In Salaries table: Emp_ID (Foreign Key referencing Employees.Emp_ID)

Example in SQL

1. Primary Key Example (Employees Table)

CREATE TABLE Employees (
    Emp_ID INT PRIMARY KEY,
    Name VARCHAR(50)
);
  • Emp_ID is the Primary Key, ensuring each employee has a unique identifier.

2. Foreign Key Example (Salaries Table)

CREATE TABLE Salaries (
    Salary_ID INT PRIMARY KEY,
    Emp_ID INT,
    Amount DECIMAL(10,2),
    FOREIGN KEY (Emp_ID) REFERENCES Employees(Emp_ID)
);
  • Emp_ID in Salaries is a Foreign Key linking to Emp_ID in Employees, ensuring data consistency.

No comments:

Post a Comment

how to create dml dynamically in Ab-initio

 $[ begin let int i = 0; let string(int) complete_list = "emp_nm,billable,age,designation,location"; let string(int) file_content ...