#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 9 of 29easy

What is the difference between Primary Key and Foreign Key?

Understanding table relationships.

What You'll Learn

  • Primary Key definition
  • Foreign Key definition
  • How they relate

Primary Key

Uniquely identifies each row in a table.

query.sqlSQL
CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  email VARCHAR(255) UNIQUE,
  name VARCHAR(100)
);

-- Composite primary key
CREATE TABLE order_items (
  order_id INT,
  product_id INT,
  quantity INT,
  PRIMARY KEY (order_id, product_id)
);

Properties:

  • Must be unique
  • Cannot be NULL
  • One per table
  • Often auto-incremented

Foreign Key

References a primary key in another table.

query.sqlSQL
CREATE TABLE orders (
  id INT PRIMARY KEY AUTO_INCREMENT,
  user_id INT,
  total DECIMAL(10,2),
  FOREIGN KEY (user_id) REFERENCES users(id)
);

-- With actions
CREATE TABLE orders (
  id INT PRIMARY KEY,
  user_id INT,
  FOREIGN KEY (user_id) REFERENCES users(id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

Referential Actions:

  • CASCADE: Delete/update related rows
  • SET NULL: Set to NULL
  • RESTRICT: Prevent deletion
  • NO ACTION: Similar to RESTRICT

Comparison

FeaturePrimary KeyForeign Key
UniquenessMust be uniqueCan have duplicates
NULLNot allowedAllowed (usually)
Per tableOne onlyMultiple allowed
PurposeIdentify rowReference other table