Introduction to databases and persistence

The Relational Model

SQL Basics, DDL, and DML

Querying Data

Advanced Concepts

Sqlite

Glossary of Database Terms

Practice

Assignment

Core program

Thinking in Relations

In a Relational Database (RDBMS), data is organized into Tables. This structure helps avoid repeating data and keeps it accurate.

The Anatomy of a Table

Imagine a spreadsheet for a simple "Students" list:

id first_name last_name email age
1 John Doe [email protected] 25
2 Jane Smith [email protected] 22

Data Types

In JavaScript, variables can hold any type of data. In a database, **Columns** are strict. You must decide what type of data goes in a column.

Constraints

Constraints are rules for your data. They ensure the data is good quality.


Keys: Connecting the Data

The "Relational" part comes from how we link tables together. We use Keys for this.

Primary Key (PK)

A unique ID for a specific row.

Foreign Key (FK)

A field in one table that links to the Primary Key of another table.

Example: We have Students and Classes. A student can sign up for a class. We create an Enrollments table to link them.

Table: Students

id (PK) name
1 John
2 Jane

Table: Classes

id (PK) title
101 Intro to SQL
102 Advanced JS

Table: Enrollments

id (PK) student_id (FK) class_id (FK)
1 1 (John) 101 (Intro to SQL)
2 1 (John) 102 (Advanced JS)
3 2 (Jane) 101 (Intro to SQL)

In the Enrollments table, student_id is a Foreign Key. It points to the id in the Students table.


Relationships

One-to-One

One record in Table A matches exactly one record in Table B.

One-to-Many (Most Common)

One record in Table A matches many records in Table B.

Many-to-Many

Many records in Table A match many records in Table B.


Normalization (The "Why")

Why do we split data into many tables? Why not put everything in one big "Enrollments" spreadsheet? Answer: To avoid copying data and making mistakes.

Imagine we stored the student's name in every Enrollment row:

  1. Waste: We write "John" 50 times if he takes 50 classes.
  2. Mistakes: If John changes his name to "Jon", we have to update 50 rows. If we miss one, our data is wrong.

By keeping Students in one table and just using the ID 1 in Enrollments, we only update the name in one place. This is called Normalization.


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*

Found a mistake or have a suggestion? Let us know in the feedback form.