Junior
What is a primary key (PK) and a foreign key (FK) in SQL?
sobes.tech AI
Answer from AI
Primary Key (PK) — is a column or a set of columns in a table that uniquely identifies each record (row).
- Properties:
- Every table must have a primary key.
- Values in the primary key must be unique.
- Values in the primary key cannot contain NULL.
Foreign Key (FK) — is a column or a set of columns in one table (child table) that references the primary key of another table (parent table).
- Purpose:
- Creates a relationship between two tables.
- Ensures referential integrity, guaranteeing that values in the foreign key exist in the related primary key.
CREATE TABLE parents (
parent_id INT PRIMARY KEY, -- Primary Key
name VARCHAR(255)
);
CREATE TABLE children (
child_id INT PRIMARY KEY,
parent_id INT, -- Foreign key referencing parents.parent_id
FOREIGN KEY (parent_id) REFERENCES parents (parent_id)
);