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
HomeResourcesFull Stack: Database Fundamentals
PostgreSQL & Relational DBs Primary & Foreign Keys Relationships (1:1, 1:N, N:N) Data Integrity & Constraints

Database Fundamentals for Full Stack Developers

Master how databases fit into modern full-stack web applications. Learn why application state cannot live in temporary variables, how relational tables and primary keys identify records, how foreign keys maintain referential integrity, and how backend APIs execute CRUD operations to serve dynamic frontends.

THE PERSISTENCE PRINCIPLE: A database is not just a place where data sits. It is an engine designed to guarantee durability(surviving server crashes & restarts),concurrency (thousands of users reading/writing simultaneously), and integrity (stopping corrupt or orphan data).

Browser (Frontend)User clicks & views
➔
Backend APIAuthN, Logic & Queries
➔
Database (DBMS)Tables, Keys & Persistence
➔
Result RowsStructured records
➔
JSON ResponseRendered in React UI
Relational Standards (PostgreSQL / MySQL / SQLite)
Full Stack Architecture
Est. Time: ~45 Mins
Curriculum Outline (11 Core Sections)
1. What is a Database? 2. Database vs DBMS 3. Relational Database Basics4. 🔥 Primary Key & Inspector 5. 🔥 Relationships (1:1, 1:N, N:N)6. 🔥 Foreign Keys & Integrity 7. 🔥 Live Relationship Playground 8. CRUD in Full Stack 9. 🔥 Database + Backend Architecture 10. Database Constraints 11. 🔥 Final Schema Design Challenge

1. What is a Database?

Why applications cannot survive on temporary frontend or backend memory

A database is an organized, structured collection of information stored electronically in a computer system. In a full-stack application, databases provide persistence: ensuring that user profiles, purchased orders, and published articles remain safe even when servers reboot, traffic spikes occur, or users refresh their browser tabs.

Temporary Memory (RAM / Variables)

Variables like const users = [] in a Node.js server or useState() in React live strictly in volatile memory.

Ephemeral / Volatile

• Data is wiped instantly when the server restarts or deploys.
• Cannot be shared across multiple server instances (horizontal scaling).
• If the server runs out of memory, the application crashes.

Database Persistence (Disk / SSD)

Data is written to persistent storage with write-ahead logging (WAL) and ACID guarantees.

Durable / Scalable

• Survives power outages, container restarts, and system crashes.
• Multi-user concurrency: Thousands of users can query simultaneously.
• Handles gigabytes to petabytes of structured records efficiently.

Realistic Domain Example: Pathubs Learning Platform
Think about an online learning system:
• Users: Stores student and teacher credentials, billing status, and profile bio.
• Courses: Stores course titles, descriptions, and instructor IDs.
• Lessons: Stores video URLs, lesson orders, and markdown text.
• Progress: Tracks which specific lessons student Alex has completed.
Without a database, every time the backend server deployed a bug fix, all user accounts and course enrollments would be permanently erased!

2. Database vs Database Management System (DBMS)

Distinguishing the stored data from the software engine that manages it

Developers often use the word "database" casually, but technically there is a vital distinction between the data and the software engine:

Database (The Data)

The actual physical files, tables, records, and binary indexes organized and persisted onto storage disks.

// The Data Structure
/var/lib/postgresql/data/base/16384/...
- Users Table: 4,500 rows
- Courses Table: 120 rows
- Enrollments: 18,200 rows
DBMS (The Engine Software)

The sophisticated software that runs as a background daemon, accepts SQL queries, enforces constraints, handles authentication, and writes to disk.

// Popular Production DBMS Engines:
• PostgreSQL: Robust, enterprise-grade, advanced types
• MySQL / MariaDB: Ubiquitous web standard
• SQLite: Lightweight, embedded in a single file
Client-Server DBMS vs Embedded DBMS
PostgreSQL & MySQL run as standalone server services listening on a network port (e.g. 5432 or 3306). Your backend connects to them over TCP.
SQLite is embedded directly inside your application code as a library reading from a single file on disk (perfect for local development, mobile apps, and micro-tools).

3. Relational Database Basics

The fundamental structural hierarchy: Database ➔ Tables ➔ Rows ➔ Columns

Relational databases model data using a 2D grid structure analogous to spreadsheets, but with strict data types, constraints, and relationship guarantees:

DatabasePlatform container
➔
TableCollection of entity records
➔
ColumnAttribute with a data type
➔
Row (Record)Single instance of data
id (Column: Integer)name (Column: Text)email (Column: Text)role (Column: Text)
101 (Row 1)Alex Riveraalex@example.cominstructor
102 (Row 2)Beatrice Chenbeatrice@example.comstudent
103 (Row 3)Carlos Mendezcarlos@example.comstudent
Table Definition

A collection of related rows representing a single real-world concept (e.g., users, courses, invoices).

Row (Record / Tuple)

One single individual instance of that entity. Row #101 is Alex Rivera; Row #102 is Beatrice Chen.

Column (Field / Attribute)

A designated characteristic possessed by every record in the table, bound to a strict data type (e.g. INTEGER, VARCHAR, BOOLEAN).

4. 🔥 Primary Key & Inspector

Uniquely identifying every record and preventing identity confusion

In human life, two people might share the exact same full name ("Alex Smith") or change their email address. In a relational database, every record needs a dependable, unchanging identifier called a Primary Key.

The Two Iron Rules of a Primary Key
1. Strictly UNIQUE: No two rows in the same table can ever share the same primary key.
2. Strictly NOT NULL: A row cannot exist without a primary key value.

Interactive Table Inspector: Spot the Integrity Violations

Click any cell below to audit it against database rules

A junior developer populated this draft users table without enabling database constraints. Click on the cells to find where Primary Key rules are being violated.

id (Candidate PK)nameemailstatus
101Alex Riveraalex@example.comActive
102Beatrice Chenbeatrice@example.comActive
101 ⚠️ [Duplicate!]Carlos Mendezcarlos@example.comPending
NULL ⚠️ [Missing!]Devon Pateldevon@example.comActive

5. 🔥 Relationships (1:1, 1:N, N:N)

Connecting tables together to model complex real-world systems

A single table cannot represent an entire web application. Relational databases excel because they allow distinct tables to link to each other through mathematical relationships:

1:1One-to-One Relationship

Each record in Table A relates to exactly one record in Table B.

Example: User ➔ Profile
One user has one private profile with settings. Keeping heavy bio/avatar details in a separate profile table improves query performance.
1:NOne-to-Many Relationship

One record in Table A relates to multiple records in Table B.

Example: Instructor ➔ Courses
One instructor (Alex) authors multiple courses. Each course stores a single instructor_id foreign key.
N:NMany-to-Many Relationship

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

Example: Students ↔ Courses
One student takes many courses; one course contains many students. This requires a junction table!
Why Many-to-Many Requires a Junction Table
You cannot store a list of course IDs inside a single student row (violates relational first normal form and destroys indexing). Instead, relational databases introduce a junction table (also called a link or join table): enrollments (id, user_id, course_id, enrolled_at). This cleanly splits the Many-to-Many relationship into two simple One-to-Many relationships!

6. 🔥 Foreign Keys & Referential Integrity

How databases enforce connections between tables and prevent orphan records

A Foreign Key is a column in one table that references the Primary Key of another table. It is the technical mechanism that binds tables together and guarantees referential integrity.

Parent Table: users
// PRIMARY KEY
id: 101  (Alex Rivera)
id: 102  (Beatrice Chen)

The referenced table whose primary key establishes the authoritative identity.

Child Table: courses
// FOREIGN KEY REFERENCES users(id)
id: 1, title: "JavaScript", instructor_id: 101  // ✓ Valid (Alex)
id: 2, title: "PostgreSQL", instructor_id: 999  // ❌ REJECTED!

The referencing table that holds the foreign key pointer.

What is an "Orphan Record"?
Imagine an enrollment row: { user_id: 999, course_id: 1 }, but user 999 does not exist in the database! This is an orphan record. If a backend query tries to fetch the student name to generate an invoice, it receives null and crashes the application with TypeError: Cannot read properties of undefined. Foreign key constraints stop this by physically forbidding the insertion of non-existent parent IDs at the database layer.

7. 🔥 Live Database Relationship Playground

Genuinely interactive multi-table schema with real-time referential integrity checks

Interact with this live 3-table database model. Add new users and courses, connect them through theenrollments junction table, and intentionally trigger a foreign key violation to observe how the database engine protects data integrity.

usersPK: id
#101 Alex Rivera
alex@example.com
instructor
#102 Beatrice Chen
beatrice@example.com
student
#103 Carlos Mendez
carlos@example.com
student
#104 Devon Patel
devon@example.com
instructor
enrollments (Junction)FKs: user_id, course_id
Enroll #1
User #102 (Beatrice)Course #1
2026-09-01
Enroll #2
User #102 (Beatrice)Course #2
2026-09-02
Enroll #3
User #103 (Carlos)Course #1
2026-09-03
coursesFK: instructor_id
#1 Full Stack JavaScript & Node.js
Instructor: Alex Rivera
Beginner
#2 PostgreSQL Database Architecture
Instructor: Devon Patel
Intermediate
#3 Modern React & Next.js Systems
Instructor: Alex Rivera
Intermediate

Create or Break Relationships Interactively:

Test Foreign Key Defense:

Quickly populate User ID with 999 (a non-existent user) to see how the database prevents corrupt orphan entries.

8. CRUD Operations in Full Stack

The 4 core operations connecting database queries directly to REST API endpoints

Virtually every full-stack feature (signing up, reading course catalogs, editing user bios, deleting accounts) maps directly to one of four fundamental database operations known as CRUD:

CREATEPOST

Adds a brand-new row into the database table.

// SQL:
INSERT INTO users (name, email)
VALUES ('Alex', 'alex@test.com');

// REST API:
POST /api/users
READGET

Queries and retrieves existing rows matching criteria.

// SQL:
SELECT * FROM users
WHERE id = $1;

// REST API:
GET /api/users/101
UPDATEPUT / PATCH

Modifies one or more attributes on an existing row.

// SQL:
UPDATE users
SET email = $1 WHERE id = $2;

// REST API:
PATCH /api/users/101
DELETEDELETE

Removes one or more rows permanently from the table.

// SQL:
DELETE FROM users
WHERE id = $1;

// REST API:
DELETE /api/users/101

9. 🔥 Database + Backend Architecture

The complete request-response flow and why browsers must NEVER connect directly to databases

A common beginner question is: "Why can't my React frontend query the PostgreSQL database directly over the network?"

Why Browsers NEVER Connect Directly to Production Databases
1. Credential Leakage: Any connection string with a username/password placed in frontend code is readable by anyone via DevTools.
2. Zero Trust Boundary: If a client can send arbitrary SQL commands, malicious users can run DROP TABLE users; or read all customer passwords.
3. Bypassed Business Logic: Payment calculations, email verifications, and permissions must be enforced in backend code before database writes occur.

Interactive Request-Response Flow Simulator:

1. Frontend Form
User submits data
2. HTTP Request
POST /api/register
3. Backend Server
Validates & checks Auth
4. SQL Execution
Parameterized query
5. Database Engine
Writes row to disk
6. JSON Response
HTTP 201 Created
7. UI Rendered
Success badge shown

Step 1: Frontend User Interaction— The student types their email and password into an HTML/React form on Pathubs and clicks "Sign Up".

10. Database Constraints

The 4 essential database-level rules that guarantee data integrity

Constraints are rules enforced directly by the database management system. Even if a bug exists in your backend JavaScript code, database constraints act as a bulletproof safety net, refusing to store corrupt or invalid rows:

PRIMARY KEY

Uniquely identifies every record. Combines UNIQUE and NOT NULL automatically.

id SERIAL PRIMARY KEY
NOT NULL

Guarantees that a column cannot be left empty. Essential for emails, passwords, and user IDs.

username VARCHAR(50) NOT NULL
UNIQUE

Ensures that all values in this column are distinct across the table. Prevents duplicate registrations.

email VARCHAR(255) UNIQUE
FOREIGN KEY

Enforces referential integrity. Rejects rows pointing to non-existent parent records.

user_id INTEGER REFERENCES users(id)

11. 🔥 Final Schema Design Challenge

Design the relational data model for an online learning platform

You are the lead full-stack engineer tasked with designing the database schema for a new online learning platform. Evaluate each architectural decision below before deploying to production.

1. Which table should store individual registered student and instructor accounts?

Data Modeling & Entity Separation

2. What should serve as the Primary Key for each user account record?

Entity Identification

3. What type of relationship exists between Students and Courses in a learning platform?

Cardinality & Relationship Modeling

4. Where should the Foreign Key for the Course Instructor be located?

One-to-Many Foreign Key Placement

5. How should the platform implement the Many-to-Many enrollment relationship?

Junction / Link Table Design

6. Which columns in the `users` table MUST have a `NOT NULL` constraint?

Data Integrity Constraints

7. Which column in the `users` table requires a `UNIQUE` constraint?

Uniqueness Integrity
The Complete Full-Stack Database Mental Model
DATABASE ➔ TABLES ➔ ROWS + COLUMNS ➔ PRIMARY KEYS ➔ RELATIONSHIPS ➔ FOREIGN KEYS ➔ CONSTRAINTS ➔ CRUD
FRONTEND ➔ HTTP API ➔ BACKEND ➔ DATABASE QUERY ➔ DATABASE PERSISTENCE ➔ BACKEND ➔ API RESPONSE ➔ FRONTEND
Persistence Over Memory

Frontend state and backend RAM vanish upon reload or server restarts. Databases ensure durable, persistent storage on disk.

Primary Keys Identifiers

Every record requires an immutable, unique identifier (e.g. id = 101) so other tables can reliably refer to it.

Foreign Keys & Integrity

Foreign keys eliminate orphan records by guaranteeing that referencing child records must point to existing parent rows.

Defense-in-Depth Constraints

Enforcing NOT NULL, UNIQUE, and CHECK at the database layer shields your data from application code bugs.