Sobes.tech
Middle+

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

sobes.tech AI

Answer from AI

Primary Key — is a unique identifier for a record in a database table. It guarantees the uniqueness of each row and cannot contain NULL.

Foreign Key — is a field (or set of fields) in one table that references the primary key of another table. It ensures referential integrity by linking records between tables.

Example:

CREATE TABLE Users (
  UserID INT PRIMARY KEY,
  UserName VARCHAR(100)
);

CREATE TABLE Orders (
  OrderID INT PRIMARY KEY,
  UserID INT,
  FOREIGN KEY (UserID) REFERENCES Users(UserID)
);

Here, UserID in the Users table is the primary key, and UserID in the Orders table is a foreign key referencing the user who placed the order.

What is the difference between a primary key and a… - sobes.tech