Primary Key vs Foreign Key in SQL

// Quick Answer
  • A Primary Key uniquely identifies each row in a table.
  • A Foreign Key links one table to another.
  • Primary Key values must be unique and not null.
  • Foreign Keys can repeat and reference Primary Keys.
  • They are used together to build relationships between tables.

What is a Primary Key?

A Primary Key is a column (or set of columns) in a table that uniquely identifies each record. No two rows can have the same primary key value, and it cannot be NULL.

💡 Simple idea

A Primary Key is like an ID card — it uniquely identifies one record in a table.

Example: Primary Key

SQL
CREATE TABLE Users (
    id INT PRIMARY KEY,
    name VARCHAR(100)
);

Here, id uniquely identifies each user.

What is a Foreign Key?

A Foreign Key is a column that creates a link between two tables. It refers to the Primary Key in another table.

💡 Simple idea

A Foreign Key is like a reference — it connects one table to another.

Example: Foreign Key

SQL
CREATE TABLE Orders (
    order_id INT PRIMARY KEY,
    user_id INT,
    FOREIGN KEY (user_id) REFERENCES Users(id)
);

Here, user_id in the Orders table refers to id in the Users table.

Primary Key vs Foreign Key

  • 🔑 Primary Key uniquely identifies a record in its own table
  • 🔗 Foreign Key connects to a Primary Key in another table
  • 🚫 Primary Key cannot be NULL; Foreign Key can be NULL (if allowed)
  • 📌 Primary Key values must be unique; Foreign Key values can repeat

Real-world example

Think of a database like an online store:

  • Users table → user_id (Primary Key)
  • Orders table → user_id (Foreign Key)

One user can have many orders, but each order belongs to only one user.

Why they matter

  • 🛡️ Ensure data integrity
  • 🔗 Create relationships between tables
  • ⚙️ Prevent duplicate or invalid data
  • 📊 Enable efficient database design
📌 Real-world fact

Every modern relational database (MySQL, PostgreSQL, SQL Server) relies heavily on primary and foreign keys to structure data properly.

Summary

A Primary Key uniquely identifies a row in a table, while a Foreign Key connects that table to another. Together, they form the backbone of relational databases.

In short: Primary Key = identity, Foreign Key = relationship.