Hackforge Academy

Category: java

what is foreign key in db and why is needed

Published on 04 May 2026

Explanation

A foreign key in a database is a column (or set of columns) in one table that refers to the primary key in another table. It is used to establish a relationship between two tables.

Code:

-- Example
CREATE TABLE Department (
    dept_id INT PRIMARY KEY,
    dept_name VARCHAR(50)
);

CREATE TABLE Employee (
    emp_id INT PRIMARY KEY,
    emp_name VARCHAR(50),
    dept_id INT,
    FOREIGN KEY (dept_id) REFERENCES 
Department(dept_id)
);

Explanation

A foreign key ensures referential integrity, meaning the value in the child table must exist in the parent table. You cannot insert invalid or non-existing references.

Code:

-- This will fail if dept_id does not exist
 in Department
INSERT INTO Employee VALUES (1, 'John', 10);

Explanation

Foreign keys are needed to maintain consistency between related tables and to prevent orphan records (records without a valid reference).

Code:

-- Prevent deleting parent record if 
child exists
DELETE FROM Department WHERE dept_id 
= 1; -- may fail if referenced

Explanation

They also support cascading actions like ON DELETE CASCADE or ON UPDATE CASCADE to automatically update or delete related records.

Code:

-- Cascade example
FOREIGN KEY (dept_id) 
REFERENCES Department(dept_id)
ON DELETE CASCADE;

Explanation

Real-time usage: Foreign keys are widely used in applications like e-commerce (orders linked to users), banking (transactions linked to accounts), and school systems (students linked to classes).

Code:

-- Example
CREATE TABLE Orders (
    order_id INT PRIMARY KEY,
    user_id INT,
    FOREIGN KEY (user_id)
 REFERENCES Users(user_id)
);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community