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_IDis 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_IDinSalariesis a Foreign Key linking toEmp_IDinEmployees, ensuring data consistency.