Pathubs Logo Mark
PATHUBSFREE CAREER ROADMAPS
HomeExploreDiscoverCompare ⚖️My Progress 📊Support
Student Support & Feedback

Have Questions or Need Help?

Have questions, feedback, or suggestions for new roadmaps and interactive tools? Reach out to our team — we review every message to make practical learning better for everyone.

supportpathubs@gmail.com Official Telegram Support (@PathubsSupport)
Pathubs

100% Free, Zero-Paywall Tech Career Roadmaps, In-Depth Practical Content, and Live Interactive Virtual Labs for Learners Worldwide.

Popular Careers

  • Frontend Development
  • Backend Development
  • AI & LLM Engineering
  • Full Stack Web Dev
  • Data Analytics

Platform Tools

  • Career Discovery Quiz
  • Compare Careers

Contact & Info

  • About Us
  • supportpathubs@gmail.com
  • Support Pathubs

© 2026 Pathubs. All Rights Reserved. Structured learning, practical content, and hands-on practice for learners worldwide.

AboutPrivacy PolicyTerms & ConditionsSitemapRobots
Home/Resources/Full Stack: Tables & Relationships
Relational Data Modeling Primary & Foreign Keys 1:1, 1:N, N:N Referential Integrity

Tables & Relationships

Master how relational database tables are structured, normalized, and connected in production web applications. Explore Primary Keys, Foreign Keys, parent-child hierarchies, and the three core relationship patterns. Experiment in a live database simulator to test referential actions, cascade deletions, and constraint violations.

🧠 The Relational Hierarchy Mental Model
Users (Parent)
1:N
Orders (Child of Users)
1:N
Order Items (Child of Orders & Products)
Full Stack Engineering Guide
PostgreSQL & MySQL Standards
Live Relationship Simulator
Zero Data Anomalies
Curriculum Outline (9 Core Sections)
01 Core Concept: Relational Foundation02 The Three Core Relationship Types03 Real-World E-Commerce Schema04 🔥 Live Relationship Playground05 Constraints & Delete Behavior06 The Full Stack Connection07 Interactive Relationship Debugging08 Mini Challenge: Learning Platform09 Short Recap & Mental Model Box
01

Core Concept: The Relational Foundation

In a relational database, a table represents a distinct real-world entity (e.g., users, products, orders). Each table is structured into rows (individual records or instances) and columns (strongly typed attributes).

Primary Key (PK)
Unique ID

A column (or set of columns) that guarantees every row in the table can be uniquely identified. A primary key must be UNIQUE and cannot be NULL.

Foreign Key (FK)
Relationship Bridge

A column in a child table that references the primary key of a parent table. It establishes a link between entities and allows the database engine to enforce connection rules.

Referential Integrity
Rule Enforcer

The database guarantee that a foreign key value must always point to an existing, valid parent row. The engine strictly prevents creating orphaned records.

Why Not Store Everything in One Huge Spreadsheet Table?Anti-Pattern Warning
-- ❌ THE "MEGA-TABLE" DISASTER: Storing user info, order info, and product info in one table:
-- user_id | user_name | user_address | order_id | order_date | product_name | product_price
-- 1       | Alex R.   | 123 Main St  | 101      | 2026-09-01 | Laptop       | $1,200.00
-- 1       | Alex R.   | 123 Main St  | 101      | 2026-09-01 | Wireless Mouse| $25.00
-- 1       | Alex R.   | 123 Main St  | 102      | 2026-09-03 | USB-C Cable  | $15.00

-- Disasters caused by this flat structure:
-- 1. Data Duplication: "Alex R." and "123 Main St" are re-written hundreds of times.
-- 2. Update Anomalies: If Alex moves, updating 1 row leaves 99 rows with obsolete addresses!
-- 3. Deletion Anomalies: Deleting order 102 accidentally erases the only record of the USB-C Cable!
02

The Three Core Relationship Types

Full-stack applications model real-world business domains using three primary relational patterns:

One-to-One (1:1)
User → Profile

A single record in Table A relates to at most one record in Table B.

Full Stack Use Case: Isolating sensitive user auth credentials (users) from optional extended public bio details (user_profiles). The foreign key has a UNIQUE constraint.

One-to-Many (1:N)
User → Orders

A single record in Table A can relate to multiple records in Table B, but each record in Table B belongs to exactly one record in Table A.

Full Stack Rule: The foreign key (user_id) always resides in the child table (orders), never in the parent table.

Many-to-Many (N:N)
Students ↔ Courses

Multiple records in Table A relate to multiple records in Table B.

The Junction Table: You cannot place a single foreign key to link N:N. You must create a bridge table (enrollments) holding student_id (FK) and course_id (FK).

03

Real-World Full Stack Example: E-Commerce Schema

Here is how an e-commerce platform links users, shopping carts, orders, and products with referential integrity:

Relational Entity Schema Diagram
usersParent Table
idPK
nameVARCHAR
emailUNIQUE
── 1:N ──>
ordersChild of Users
idPK
user_idFK → users.id
totalDECIMAL
statusVARCHAR
── 1:N ──>
order_itemsJunction Table
idPK
order_idFK → orders.id
product_idFK → products.id
quantityINT
<── 1:N ──
productsParent Table
idPK
titleVARCHAR
priceDECIMAL

When a customer clicks "Checkout" in your web app, the backend creates one entry in orders, and multiple entries in order_items, each pointing to their respective product_id.

04

🔥 Live Relationship Playground

Actively test how foreign keys protect your database. Insert valid orders, attempt invalid foreign keys to see referential constraint rejections, and test parent record deletions:

FOREIGN KEY DELETE BEHAVIOR:
Database schema online. Foreign Key enforced: orders.user_id → users.id
🧑 Parent Table: `users` (3 rows)Holds Primary Key `id`
id (PK)nameemailaction
1Alex Riveraalex@example.com
2Sam Chensam@example.com
3Taylor Swifttaylor@example.com
📦 Child Table: `orders` (3 rows)FK `user_id` → `users.id`
id (PK)user_id (FK)totalstatus
1011 ✓$149.50delivered
1021 ✓$89.00shipped
1032 ✓$299.00pending
05

Constraints & Foreign Key Delete Behaviors

Database constraints are not just theoretical rules — they are the defensive guard rails that protect your production data from being corrupted by buggy backend logic:

PRIMARY KEY

Enforces uniqueness and not-null on the identity column. Every table should possess a primary key.

FOREIGN KEY

Guarantees referential integrity: child rows cannot point to a non-existent parent ID.

NOT NULL & UNIQUE

NOT NULL guarantees data presence; UNIQUE prevents duplicate values (e.g. user emails).

What Happens When a Parent Record is Deleted? (ON DELETE Actions)

ON DELETE CASCADE

Deleting the parent row automatically deletes all corresponding child rows.

Best for: Dependent child data that has no reason to exist without the parent (e.g., deleting an Order removes its order_items).

ON DELETE RESTRICT / NO ACTION

The database halts and throws an error if any child row references this parent.

Best for: High-value business records (e.g., preventing deletion of a users account if historic financial transactions or tax invoices exist).

ON DELETE SET NULL

The child row is preserved, but its foreign key column is updated to NULL.

Best for: Optional relationships (e.g., if an author is deleted, their blog posts remain with author_id = NULL).

06

The Full Stack Connection: From Frontend to JOIN Query

How do relational tables translate into real-world web experiences? When a user navigates to their profile page in a React app, here is the exact full-stack pipeline:

GET /api/users/42/orders Request-Response PipelineBackend Route Handler
// 1. Frontend sends HTTP Request:
// GET https://api.myshop.com/users/42/orders

// 2. Node.js Backend receives request and executes an SQL JOIN:
SELECT 
  u.id AS user_id, 
  u.name, 
  o.id AS order_id, 
  o.total, 
  o.status
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.id = 42;

// 3. Database utilizes the Foreign Key index to rapidly match rows.
// 4. Backend serializes the related rows into structured JSON:
{
  "user_id": 42,
  "name": "Alex Rivera",
  "orders": [
    { "order_id": 101, "total": 149.50, "status": "delivered" },
    { "order_id": 102, "total": 89.00, "status": "shipped" }
  ]
}

// 5. React Frontend receives the JSON and renders the User Order Dashboard!
07

Interactive Relationship Debugging: Diagnose Real Errors

Analyze real database error messages encountered in production. Diagnose the root cause and learn the defensive remedy:

Bug 1: Foreign Key References Non-Existent RecordDatabase Log Output
ERROR: insert on table "enrollments" violates foreign key constraint "fk_enrollment_course"
Detail: Key (course_id)=(999) is not present in table "courses".

Why did the database engine reject this INSERT statement?

Bug 2: Many-to-Many Relationship Without a Junction TableDatabase Log Output
DESIGN ERROR: Attempted to store comma-separated course IDs inside users: "10,24,35"
Consequence: Cannot enforce foreign keys, impossible to index, painful JOIN queries.

How should a Many-to-Many relationship between Students and Courses be correctly designed?

Bug 3: Inserting NULL into a NOT NULL Foreign KeyDatabase Log Output
ERROR: null value in column "user_id" of relation "orders" violates not-null constraint
Detail: Failing row contains (204, null, 75.00, 'pending').

What is the consequence of marking a foreign key column as NOT NULL in orders?

Bug 4: Duplicate Primary Key InsertionDatabase Log Output
ERROR: duplicate key value violates unique constraint "users_pkey"
Detail: Key (id)=(1) already exists.

What fundamental rule of relational databases was violated?

08

Mini Challenge: Design the Learning Platform Database

Put your relational architectural knowledge to the test. Design the database schema for a learning platform with Users, Courses, Lessons, and Enrollments:

Design Task 1 of 5Score: 0 / 5
Architectural Step #1
1. In a Learning Platform database (Users, Courses, Lessons, Enrollments), what is the relationship between Courses and Lessons?
Section 9: Short Recap & Mental Model

Remember these core relational principles on every full-stack project you build:

1. Table = Entity Model

A table represents a discrete business entity (Users, Orders, Products). Never combine disparate entities into one massive table.

2. Primary Key = Unique Identity

Every row must have a unique identifier (usually an auto-generated integer or UUID) that never changes.

3. Foreign Key = Relationship Bridge

Foreign keys reside on the child table, pointing back to the parent's primary key.

4. One-to-Many = Standard Link

One parent relates to many children. The child table stores the parent's primary key (e.g., orders.user_id).

5. Many-to-Many = Junction Table

Requires an intermediate bridge table with two foreign keys (e.g. enrollments bridging users and courses).

6. Constraints = Integrity Protection

NOT NULL, UNIQUE, and ON DELETE (CASCADE / RESTRICT) enforce business rules directly at the database engine level.