Junior — Middle
What is the difference between a primary key and a foreign key in a database, and how are they used?
sobes.tech AI
Answer from AI
Primary Key — is a unique identifier for each record in a database table. It guarantees that each row is unique and allows for quick data retrieval. Usually, a primary key cannot be NULL and must be unique.
Foreign Key — is a field (or set of fields) in one table that references the primary key of another table. It is used to establish and maintain relationships between tables, ensuring data integrity.
Example:
CREATE TABLE Users (
UserID INT PRIMARY KEY,
UserName VARCHAR(100)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
UserID INT,
OrderDate DATE,
FOREIGN KEY (UserID) REFERENCES Users(UserID)
);
Here, UserID in the Users table is the primary key, and UserID in the Orders table is the foreign key that links an order to a specific user.