SQL Commands - Primary Key vs Foreign Key — Vista Academy

Primary Key vs Foreign Key — Difference, Rules & SQL Examples

Clear definitions, side-by-side comparison, practical SQL examples, and answers to common questions like can a primary key be a foreign key or can a foreign key be NULL. Hybrid English + Hindi guide — 2025 update.

Why PK & FK matter

Primary Keys (PK) uniquely identify rows; Foreign Keys (FK) link tables and enforce referential integrity. This section answers high-volume queries such as primary key and foreign key, difference between primary key and foreign key, and primary key vs foreign key in SQL.

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

🔑 What is a Primary Key?

A Primary Key (PK) uniquely identifies each row in a table. It must be unique and NOT NULL. Databases typically index PKs for both integrity and performance.

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

🔗 What is a Foreign Key?

A Foreign Key (FK) is a column in one table that references the Primary Key (or a UNIQUE key) of another table to enforce relationships and referential integrity.

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

⚖️ Difference between Primary Key and Foreign Key

Side-by-side comparison for quick answers to search queries.

Aspect Primary Key Foreign Key
UniquenessUnique & NOT NULLNullable & may repeat
PurposeIdentify rowsLink tables
Count per tableOne (composite allowed)Multiple allowed
EnforcesEntity integrityReferential integrity

❓ Can a Primary Key be a Foreign Key?

Yes — in some designs (1:1 relationships or identifying/weak-entity models) a primary key can also serve as a foreign key.

CREATE TABLE Employees ( employee_id INT PRIMARY KEY, name VARCHAR(100) );
CREATE TABLE EmployeeDetails ( employee_id INT PRIMARY KEY, details TEXT, FOREIGN KEY (employee_id) REFERENCES Employees(employee_id) );

❓ Can a Foreign Key be NULL or have duplicate values?

NULL: Yes, unless NOT NULL is specified.
Duplicate: Yes — multiple child rows can reference the same parent row (answers queries like “is foreign key unique?”).

🧾 Practical SQL Examples

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

— Orders 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 );

📌 TL;DR

Primary Key = unique identifier (NOT NULL). Foreign Key = reference to parent (nullable/duplicates allowed). Design PK/FK carefully for integrity and joins.

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

⚖️ Primary Key vs Foreign Key — Quick Comparison ( primary key vs foreign key)

This comparison answers common queries like difference between primary key and foreign key,
is foreign key unique, and primary key vs foreign key in SQL. Use this as a quick reference
when designing database tables and ER diagrams.

At a glance
PK = uniqueness & identity
FK = relationships & integrity

Feature Primary Key (PK) Foreign Key (FK)
Definition Uniquely identifies each row within the same table References the PK (or UNIQUE) of another table to create relationships
NULL Allowed? No — PK must be NOT NULL Yes — unless explicitly constrained as NOT NULL
Duplicates? No — values are unique Allowed — many child rows can reference the same parent
Count per table One PK per table (composite keys possible) Multiple FKs allowed (to different parent tables)
Purpose Row identity, indexing, fast lookups Enforce referential integrity and support joins
Example Students.student_id Marks.student_id → Students.student_id

This table targets queries like primary key vs foreign key, difference between primary and foreign key,
primary key foreign key example, and is foreign key unique. For practical SQL examples and ER-diagram tips, refer to the next section of the guide.

Tip: index FK columns used frequently in JOINs to improve performance.

🧾 See SQL Examples

🔄 Can a Primary Key be a Foreign Key? (With SQL Examples)

Many learners ask: can a primary key be a foreign key? The answer is Yes. In SQL database design, a primary key (PK) can also serve as a foreign key (FK), especially in 1-to-1 relationships or self-referencing hierarchies. Below are two practical examples with SQL code.

👨‍👩‍👧 Self-Referencing Table (Manager → Employee)

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

Here emp_id is the table’s Primary Key. The manager_id column is a Foreign Key pointing back to the same PK, creating a hierarchical relationship.

🧩 Primary Key as Foreign Key (1-to-1 Relationship)

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),
  FOREIGN KEY (user_id) REFERENCES Users(user_id)
);

In this case UserProfiles.user_id is both Primary Key and Foreign Key, ensuring a strict one-to-one mapping with Users.

Keywords covered: primary key as foreign key, can primary key be foreign key, primary key foreign key example in SQL.

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

1) Create Tables with Primary Key & Foreign Key

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
);
        

Here, Orders.customer_id is a Foreign Key referencing Customers.customer_id. ON DELETE SET NULL means the FK becomes NULL when the parent row is removed.

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');
        

Always insert parent rows (Customers) before child rows (Orders) to satisfy FK constraints.

3) Join Tables using PK–FK Relationship

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

This SQL join retrieves order details along with customer names by using the Primary–Foreign Key relationship.

Keywords covered: primary key and foreign key in SQL with examples, sql primary key foreign key example, how to use primary key and foreign key in SQL, difference between primary and foreign key in SQL.

🧭 Real-World Use Cases — Primary Key & Foreign Key in Action

See how primary keys and foreign keys are used in production systems — from retail to healthcare. These practical examples clarify why primary key vs foreign key design matters for data integrity, reporting, and performance.

🏪 Retail — Orders & Inventory

Use Customers.customer_id (PK) and Orders.customer_id (FK) to link purchases to buyers. FK cascade rules help keep order history consistent when customer records change.

  • Use PKs for fast lookup of customers and products.
  • Index FK columns used in JOINs for performance.

🏦 Banking — Accounts & Transactions

Accounts use a PK (account_id) while Transactions reference it via an FK. Referential integrity ensures transactions cannot reference deleted accounts.

  • Enforce FK constraints to maintain ledger accuracy.
  • Use partitioning and indexes to scale transaction joins.

🎓 Education — Students & Enrollments

Model many-to-many relationships (Students ↔ Courses) with a join table using a composite PK (student_id, course_id) while each column references the parent PKs as FKs.

  • Composite PKs prevent duplicate enrollments.
  • FKs let you quickly generate student/course reports.

🏥 Healthcare — Patients & Records

Patient records use a stable primary key (e.g., patient_id). Appointments, prescriptions and lab results reference this PK with FKs to maintain an auditable history.

  • FKs help maintain legal and audit trails.
  • Careful FK design prevents orphaned clinical data.

📊 Analytics — Fact & Dimension Tables

In star schemas, dimension tables have PKs used as FKs in fact tables (e.g., dim_date.date_id → fact_sales.date_id). This makes aggregations and joins fast and consistent.

  • Denormalize only when necessary for query speed.
  • Keep PKs stable (surrogate keys) to simplify ETL.

These use cases show why careful primary key and foreign key design is essential for data integrity, query performance, and maintainability. Apply appropriate cascade rules, indexing, and constraints based on business rules.

🎯 Learn Practical DB Design at Vista Academy

🌍 Real-World Applications of Primary & Foreign Keys

Primary Keys (PK) and Foreign Keys (FK) are the foundation of relational databases. They ensure data integrity, prevent duplicates, and enable relationships between entities. Here are some common real-world scenarios:

🏪 Retail Systems

Customers (PK) linked to Orders (FK). Ensures each order belongs to a valid customer and enables order history tracking.

🏦 Banking

Accounts (PK) connected to Transactions (FK). Guarantees that every transaction is tied to an existing account.

🎓 Education

Students (PK) linked to Enrollments and Courses (FK). Maintains consistency in academic records and course registrations.

🚚 Logistics

Shipments (PK) linked to Delivery Tracking (FK). Keeps data consistent across warehouses, routes, and delivery status updates.

Keywords: why do relational databases use primary keys and foreign keys, primary key foreign key examples, real-world use of primary and foreign key

❓ 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