The Relational Model
Understand tables, rows, primary and foreign keys, constraints and relationships before writing any SQL.
Beginner · about 4 hours · difficulty 2/5
A relational database stores data in tables (relations). Each row is one record and each column has a type. The power comes from linking tables through keys instead of duplicating data.
Key ideas
- Primary key: a column (or set of columns) that uniquely identifies a row, such as
id. Common choices are auto-incrementing integers or UUIDs. - Foreign key: a column that references another table's primary key, for example
orders.user_id -> users.id. The database enforces that the referenced row exists. - Relationships: one-to-one, one-to-many (a user has many orders) and many-to-many (students and courses, modeled with a join table).
- Constraints:
NOT NULL,UNIQUE,CHECKand foreign keys let the database guard your data even when application code has bugs.
Why relational first
Most business data (users, orders, payments, bookings) is naturally relational, and relational databases give you strong consistency, flexible querying and decades of tooling. Start here and add other stores when you have a concrete reason.
Pitfalls
- Skipping constraints "for flexibility". Bad data is far more expensive than a failed insert.
- Storing comma-separated lists in a column instead of using a related table.
You are ready to move on when you can draw an entity-relationship diagram for a small app (for example a blog with users, posts, comments and tags) and name every key and constraint.
Key concepts
- Tables, rows and column types
- Primary keys (serial vs UUID)
- Foreign keys and referential integrity
- One-to-many and many-to-many
- Constraints: NOT NULL, UNIQUE, CHECK
- ER diagrams
Mini project
Design the schema for a library system (members, books, copies, loans) as an ER diagram, then write the CREATE TABLE statements with all keys and constraints.
Check yourself
How would you model tags on blog posts, and why not store them as a comma-separated string?
Free resources
- PostgreSQL tutorial: the SQL language (PostgreSQL)
- freeCodeCamp: database design articles (freeCodeCamp)