🌟 Introduction

Relational databases depend on structured relationships to keep data accurate and meaningful. Two pillars of that structure are the Primary Key (PK) and the Foreign Key (FK). PK ensures each row is uniquely identifiable; FK connects tables and enforces referential integrity. This hybrid guide (English + Hindi) helps you master both concepts and apply them in real projects.

Quick Hindi Summary:
Primary Key: किसी तालिका का वह कॉलम जो प्रत्येक रिकॉर्ड को यूनिक पहचान देता है (NULL नहीं हो सकता)।
Foreign Key: वह कॉलम जो दूसरी तालिका की Primary Key को संदर्भित करता है और तालिकाओं को जोड़ता है।

🔑 What is a Primary Key?

A Primary Key is a column or set of columns that uniquely identifies each row in a table. It must be unique and not null. Most DB engines automatically index primary keys for fast lookups.

CREATE TABLE Students (
  student_id INT PRIMARY KEY,
  name VARCHAR(100),
  dob DATE
);

🔗 What is a Foreign Key?

A Foreign Key is a column (or set) in one table that refers to the Primary Key (or a UNIQUE key) in another table. It maintains relationships and enforces referential integrity.

CREATE TABLE Orders (
  order_id INT PRIMARY KEY,
  customer_id INT,
  order_date DATE,
  FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

⚖️ Primary Key vs Foreign Key — Quick Comparison

Feature Primary Key Foreign Key
UniquenessUnique & NOT NULLMay be duplicate / NULL
PurposeIdentify rowsLink tables
Per tableOne (composite allowed)Multiple allowed
IndexingUsually indexedMay not be indexed
IntegrityNoEnforces referential integrity

🧾 Practical SQL Examples

-- Customers table
CREATE TABLE Customers (
  customer_id INT PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100) UNIQUE
);

-- Orders table referencing Customers
CREATE TABLE Orders (
  order_id INT PRIMARY KEY,
  customer_id INT,
  order_date DATE,
  amount DECIMAL(10,2),
  FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

-- OrderItems with cascade delete
CREATE TABLE OrderItems (
  item_id INT PRIMARY KEY,
  order_id INT,
  product_id INT,
  qty INT,
  FOREIGN KEY (order_id) REFERENCES Orders(order_id) ON DELETE CASCADE
);

⚙️ Advanced: PK as FK & Composite Keys

-- Example: child table where PK is also FK
CREATE TABLE EmployeeDetails (
  employee_id INT PRIMARY KEY,
  details JSON,
  FOREIGN KEY (employee_id) REFERENCES Employees(employee_id)
);

🔁 Cascading Actions

  • CASCADE – delete/update child rows automatically
  • SET NULL – set FK value to NULL
  • RESTRICT / NO ACTION – prevent parent change if child exists

🏪 Retail

Customers → Orders → OrderItems. Use FK to link orders to customers; cascade rules for order cleanup.

🏦 Banking

Accounts → Transactions. PK for account numbers; FK in transactions to maintain ledger integrity.

🎓 Education

Students → Enrollments → Courses. Composite PK for enrollment (student_id, course_id).

❓ अक्सर पूछे जाने वाले प्रश्न (Hindi FAQs)

Q: Primary Key और Foreign Key में क्या अंतर है?
A: Primary Key तालिका में हर रिकॉर्ड को यूनिक पहचान देता है; Foreign Key तालिकाओं को जोड़ता है और referential integrity लागू करता है.

Q: क्या Foreign Key NULL हो सकती है?
A: हाँ, जब तक NOT NULL constraint न लगाया गया हो.

Q: क्या एक तालिका में एक से अधिक Foreign Keys हो सकती हैं?
A: हाँ — एक तालिका में कई FK हो सकते हैं जो विभिन्न parent तालिकाओं को संदर्भित करते हैं.

✅ Summary — Quick Checklist

  • Use Primary Key to uniquely identify rows (NOT NULL & UNIQUE).
  • Use Foreign Key to connect tables and enforce referential integrity.
  • Consider cascading rules carefully — choose CASCADE/SET NULL/RESTRICT based on business needs.
  • Index frequently joined FK columns for performance.
  • Use composite keys for many-to-many join tables (or bridge tables).

🎓 Learn SQL with Vista Academy

Join our practical Data Analytics program in Dehradun — live projects, placement support & doubt sessions. Master SQL, database design and analytics with real-world assignments.

© Vista Academy • Content updated 2025 • Built with Vista Theme — dark, golden & elegant UX for learners.

⚖️ Primary Key vs Foreign Key (Difference Table)

Feature Primary Key (PK) Foreign Key (FK)
Definition Uniquely identifies each row in its own table References PK of another (or same) table
NULL Allowed? No Yes (unless constrained)
Duplicates? No (always unique) Allowed (many rows can reference same PK)
Count per Table One PK (can be composite) Many FKs allowed
Purpose Row identity & indexing Relational integrity between tables
Example Students.student_id Marks.student_id → Students.student_id

Keywords: primary key vs foreign key, difference between primary and foreign key, foreign key vs primary key in SQL

🔄 Can a Primary Key be a Foreign Key?

Yes. In a different table, the Primary Key value can appear as a Foreign Key. In the same table, a column can participate in both PK and FK roles (e.g., self-referencing hierarchies) but typically as part of different constraints.

👨‍👩‍👧 Self-Reference (Manager → Employee)

CREATE TABLE Employees (
  emp_id     INT PRIMARY KEY,
  name       VARCHAR(100),
  manager_id INT,
  CONSTRAINT fk_emp_manager
    FOREIGN KEY (manager_id) REFERENCES Employees(emp_id)
);
      

Here, emp_id is the PK. The manager_id column is an FK referencing the same table’s PK.

🧩 PK of Child = FK to Parent (1-to-1)

CREATE TABLE Users (
  user_id INT PRIMARY KEY,
  email   VARCHAR(100) UNIQUE
);

CREATE TABLE UserProfiles (
  user_id INT PRIMARY KEY, -- also FK
  bio     VARCHAR(200),
  CONSTRAINT fk_profile_user
    FOREIGN KEY (user_id) REFERENCES Users(user_id)
);
      

UserProfiles.user_id is both PK and FK, enforcing a strict 1-to-1 relation.

🛠️ Using Primary & Foreign Keys in SQL (Examples)

1) Create Tables with PK & FK

CREA​TE TABLE Customers (
  customer_id INT PRIMAR​Y KEY,
  name        VARCHAR(100) NOT NULL
);

CREA​TE TABLE Orders (
  order_id     INT PRIMAR​Y KEY,
  customer_id  INT,
  order_date   DATE NOT NULL,
  CONSTRAINT fk_orders_customer
    FOREI​GN KEY (customer_id) REFERENCES Customers(customer_id)
      ON UPD​ATE CASC​ADE
      ON DEL​ETE SET NULL
);
        

Note: ON DELETE SET NULL allows FK to be NULL when parent is deleted.

2) Insert Data in Correct Order

INS​ERT INTO Customers(customer_id, name) VALUES (1, 'Asha'), (2, 'Ravi');

INS​ERT INTO Orders(order_id, customer_id, order_date)
VALUES (101, 1, '2025-08-01'), (102, 2, '2025-08-05');
        

3) Join Tables using PK–FK

SE​LECT o.order_id, c.name, o.order_date
FROM Orders o
JO​IN Customers c
  ON o.customer_id = c.customer_id;
        

Targets: primary key and foreign key in SQL with examples, sql primary key foreign key, how to use primary key and foreign key in SQL

❓ FAQs: Primary Key & Foreign Key

Does a Foreign Key have to be unique?

No. A foreign key can repeat because multiple child rows often reference the same parent row (1-to-many). Use UNIQUE if you need uniqueness on the FK column.

हिंदी: Foreign Key आमतौर पर दोहराई जा सकती है — केवल तभी यूनिक होगा जब UNIQUE constraint लगाया गया हो।

Can a Foreign Key be NULL?

Yes — unless the column is explicitly declared NOT NULL by schema or business rules. NULL FKs mean “no relationship” for that row.

हिंदी: हाँ, जब तक NOT NULL constraint न लगाया गया हो; NULL का मतलब है उस रो का कोई parent नहीं।

Must a Foreign Key reference a Primary Key?

Typically FK references a candidate key — most often the Primary Key. Many DBMS also allow referencing a UNIQUE NOT NULL key instead of the PK.

हिंदी: आमतौर पर FK, PK को संदर्भित करता है; लेकिन यह किसी UNIQUE NOT NULL कॉलम को भी रेफर कर सकता है।

Can a Primary Key also be a Foreign Key?

Yes — in certain designs (identifying relationships or strict 1:1 mappings) a PK in a child table may also be an FK to the parent table.

हिंदी: हाँ — जैसे identifying relationship में child की PK, parent की PK को रेफर कर सकती है।

Does a Foreign Key enforce referential integrity?

Yes. FK constraints prevent child rows from referencing non-existent parent rows and allow DB engines to enforce ON DELETE / ON UPDATE behaviors.

हिंदी: हाँ — FK यह सुनिश्चित करता है कि child, मौजूद parent को ही रेफर करे और cascade नियम लागू होते हैं।

Can a Foreign Key have duplicate values?

Yes. Duplicates are common for 1-to-many relationships. If you want uniqueness, add a UNIQUE constraint to the FK column (but that changes relationship cardinality).

हिंदी: हाँ — कई child रो एक ही parent का reference कर सकती हैं; UNIQUE लगाने से यह व्यवहार बदल जाता है।

What happens on parent delete (ON DELETE)?

Behavior depends on FK actions: CASCADE deletes child rows; SET NULL sets FK to NULL; RESTRICT/NO ACTION prevents the delete.

हिंदी: parent हटाने पर CASCADE child हटाएगा, SET NULL child के FK को NULL करेगा, अन्यथा delete block होगा।

Can foreign keys reference composite (multi-column) keys?

Yes. You can define composite foreign keys that reference composite primary keys — both sides must match column order and types.

हिंदी: हाँ — multi-column FK, multi-column PK को रेफर कर सकती है; कॉलम क्रम और टाइप मेल खाने चाहिए।

What uniquely identifies each row in a table?

The Primary Key. It’s the canonical identifier for rows in a relation.

हिंदी: किसी तालिका में हर रिकॉर्ड की अनन्य पहचान Primary Key होती है।

📝 Quiz: Primary Key vs Foreign Key

Answer all questions — your results and correct answers will appear when you finish.

Progress
0 / 10

🎓 Vista Academy Master Program in Data Analytics

Vista Academy’s Master Program in Data Analytics equips you with advanced skills in Data Analysis, Machine Learning, SQL, Python, Tableau, and Power BI. With hands-on projects and expert mentoring, this program prepares you for high-demand roles in Data Science and Analytics.

📍 Address: Vista Academy, 316/336, Park Rd, Laxman Chowk, Dehradun, Uttarakhand 248001

🚀 Take Your SQL Skills to the Next Level

📘 Explore Additional SQL Tutorials & Real-World Practice

Now that you’ve mastered Primary & Foreign Keys, it’s time to practice advanced SQL concepts. Explore the following tutorials and apply them on real datasets to level up your skills:

🚀 Keep practicing on real-world datasets and refining your skills. The more hands-on experience you gain, the stronger your SQL foundation will become!

Vista Academy – 316/336, Park Rd, Laxman Chowk, Dehradun – 248001
📞 +91 94117 78145 | 📧 thevistaacademy@gmail.com | 💬 WhatsApp
💬 Chat on WhatsApp: Ask About Our Courses