Database Design Full Course - How to Design a Relational Database (1.5 Hours!)

Timestamps

  • - Intro
  • - What a database actually is
  • - DBMS and RDBMS
  • - Relational, in plain words
  • - General structure for software development
  • - Embedded databases
  • - What does the database structure look like?
  • - Data integrity: what we're protecting
  • - Simple DB access wrapper
  • - Designing systems: start with sentences, not tables
  • - Nouns, verbs, and details
  • - Relationships
  • - One-to-one relationship
  • - One-to-many relationship
  • - Many-to-many relationships
  • - Using three keys
  • - Lookup table
  • - Primary keys and foreign keys
  • - Primary key
  • - Candidate key
  • - Auto-incremented ID vs GUID
  • - Foreign key
  • - When should you delete data?
  • - Normalization
  • - Normal forms
  • - First normal form (1NF)
  • - Second normal form (2NF)
  • - Third normal form (3NF)
  • - What's next?

Database design is one of those things where a little effort up front goes a long way. If you mess it up, you end up spending hours or days later fixing the design and figuring out how to enforce data integrity after the fact.

The whole video is drawn on the board, so these notes follow the same examples, mostly a video platform with users, channels, videos, comments and playlists. The video doesn't write full SQL, so I added the Postgres version under the designs. If you've worked with databases before, the first part will be review, so feel free to jump around with the timestamps.

What a database actually is

What do we store in a database? Data, which I know is incredible. More specifically, it's any info you need to persist so you can get it back later.

If you have a website or an app with a login, the system needs to check the database to know if you logged in correctly. That's user info. You'd also store events like when they logged in, their settings and preferences, and pretty much anything else they access on your site.

A database is just software installed on a server, and a server is just a regular computer (sometimes in a rack, sometimes not). That computer can be dedicated to the database or it can also run your backend. The design stuff we talk about in this video is pretty much the same either way. It only really changes once you get in to things like sharding and splitting data across regions, which is system design territory.

DBMS and RDBMS

The software you install is a database management system, or DBMS. When it's relational you'll see RDBMS. Postgres, MySQL, Oracle and SQL Server are all examples.

Relational, in plain words

Relational refers to tables. Everything is tabular data, so when you visualize it, it looks a lot like a spreadsheet with columns across the top and rows of data.

It's worth noting that "relation" formally means a table, and that's different from a "relationship" (how tables connect, which we'll cover later). A lot of people use the two words interchangeably, which is where the confusion comes from.

So why not just use a spreadsheet? It comes down to the use case and scale. A spreadsheet is something a human opens, types numbers into and runs calculations on. With a database it's usually an application that connects to it, not a person. Databases are also built with indexing for fast querying, formal relationships across tables, procedural languages, and support for a lot of connections at once.

I've seen people use spreadsheets as the backend for an app, but that's going to limit them past a certain point. If I was starting something just for fun I'd skip the spreadsheet and go straight to a small SQLite or Postgres instance, you can even run Postgres in a container.

General structure for software development

The general structure is a frontend or client that talks to a backend, and the backend is what talks to the database:

client (FE)  <->  backend (BE)  <->  database

client  --X-->  database      (connection string in the client, don't do this)

Good software engineering is to avoid connecting to the database directly when you can, because people make mistakes and that puts the data itself in jeopardy. Instead you program the exact things you want to do in software and go through that. The thing I want to call out is you should NOT go from the client straight to the database. Whether it's a website, a mobile app or a desktop app, assume the client is insecure. If you put a connection string to a shared database in the client, someone can grab it and manipulate the database in ways you don't want.

This is the structure you get with a centralized database like Postgres, MySQL, Oracle or SQL Server. Lots of clients hit the same backend, and the backend hits one shared database.

Embedded databases

What if the software isn't client/server? Say it's a local video editing app that needs to remember which files and edits exist. In that case there's usually a database just for that one install, and if someone else downloads the app they get their own separate database.

centralized                     embedded

client 1 --\                    client 1 + its own database
client 2 ---> backend -> db     client 2 + its own database
client 3 --/

That's called an embedded database, because the database is embedded in whatever system is running the software. Smart fridges, offline apps, that kind of thing. Two clients means two databases that aren't shared, so there's no centralized connection.

This is more about architecture than tables, but it matters because it can change how you design the tables. A database that supports a lot of users might have rules like "this user can't see that user's stuff", and that's a big reason the software layer in front of the database is so important. In the app you can tie access to auth, make sure the person is logged in, limit data to a region, and validate data before it ever gets to the database.

For the rest of the video we'll assume the centralized setup.

What does the database structure look like?

Some formal vocab real quick. You may not get quizzed on these in an interview, but you'll run into them, especially in school.

  • entity type - the type of thing you're describing, like a comment
  • entity - one specific instance, one comment
  • attributes - the things you care about for that entity, these become the columns

So if we had a comments table for videos, the columns might be an ID, who posted it, a timestamp and the video it's on:

comments

id poster_id ts video_id
7 32 123456 72
9 17 987664 72

videos

id
72

You might be thinking, where's the actual data? It's all just numbers. That's one of the benefits of relationships. The 72 ties to a row in a videos table with the ID of 72, and that's how we know the comment belongs to that video. Those connections are made with foreign keys, which we'll get to.

Every row also gets its own ID. That one doesn't reference anything, it describes this specific comment, so if you want to talk about one comment you can say "the comment with ID 9".

A few more synonyms you'll see: a row is also called a tuple, a record or an entry, and columns are often called attributes or fields.

Data integrity: what we're protecting

Why split data across tables and connect it with numbers? It's all to build and protect data integrity, which basically means the data is trustworthy and the structure of the database protects us from bad data getting in.

There are a few angles to think about it from:

  • Entity integrity - can I look at a row and trust it? No duplicates (the same comment isn't in there twice by mistake), and a row is dedicated to exactly one thing, not multiple comments crammed into one row.
  • Referential integrity - connections across tables. We don't want a pointer that points to nothing. If video 72 doesn't exist, that's a problem, and if someone changes it to 77 and 77 doesn't exist, the database should yell at you.
  • Domain integrity - does the value make sense for what you're representing? Data types get you the basics, then lookup tables, enums, check constraints, even stored procedures.

Here's the 77 example. In Postgres it's the REFERENCES part that makes the connection:

SQL
CREATE TABLE videos (
    id bigint PRIMARY KEY
);

CREATE TABLE comments (
    id bigint PRIMARY KEY,
    poster_id bigint NOT NULL,
    ts bigint NOT NULL,
    video_id bigint NOT NULL REFERENCES videos (id)
);

INSERT INTO videos VALUES (72);
INSERT INTO comments VALUES (7, 32, 123456, 72);

UPDATE comments SET video_id = 77 WHERE id = 7;

That last line will fail:

ERROR:  insert or update on table "comments" violates foreign key constraint "comments_video_id_fkey"
DETAIL:  Key (video_id)=(77) is not present in table "videos".

Domain integrity is often pushed up to the application. Say you have a marathon training app and the intro survey asks for your marathon time. If someone types -71, that's something you'd usually validate in the app. You can also do it in the database with a check constraint:

SQL
CREATE TABLE runners (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    marathon_minutes integer CHECK (marathon_minutes > 0)
);

How I usually start: let the database handle entity integrity, referential integrity, data types and lookup tables, and do the rest of the validation in the app. I'd only push more checks down in to the database once there's a real reason, like multiple apps hitting the same database.

Simple DB access wrapper

If two backends use the same database, now you'd have to copy that validation into both.

One option is to move the validation into the database (check constraints). Another is to write a small piece of software that sits in front of the database, does the validation, and is the only thing that reads and writes data. Then both backends go through that same gate:

backend 1 --\
             --> validation --> database
backend 2 --/

You don't need to understand every scenario, this isn't a system design video. There are just different places to enforce the same rules: the backend, the database, or a dedicated service in front of the database.

The two we really care about for design are entity and referential integrity, because those are about the structure of the database. Domain integrity is more about the values themselves and is specific to whatever you're building.

💡 Tip[!tip]
You want to never have to be careful. You should still BE careful, but the system should be fine even if you're not, because relying on people being careful means someone eventually messes up. Same reason I'd avoid having production connection strings on your local machine, even if you only use them when you need them. In bigger companies this is why there's a database administrator whose job is to set up, configure and protect the database.

Designing systems: start with sentences, not tables

Once you've done this a while you build an intuition and can kinda just do it. But for now we'll start with plain sentences about what user behavior we need to support, then break those down into tables, attributes and relationships.

Here's the list for a video platform. It's not meant to be complete, you can always add capabilities, but the more you think of up front the easier time you'll have:

  • A user can create a channel
  • A channel uploads videos
  • A user subscribes to a channel
  • A user comments on a video
  • A comment can be a reply
  • A user can create playlists and add videos to the playlist
  • Like and dislike button

Nouns, verbs, and details

Now go through that list and mark the nouns and the verbs. I square the nouns and underline the actions on the board. Here it is with the nouns in brackets:

A [user] can create a [channel]
[channel] uploads [videos]
A [user] subs to [channel]
A [user] comments on a [video]
A [comment] can be a reply
A [user] can create [playlists] + add [vids] to [playlist]
like + dislike button
  • Nouns will likely become tables
  • Verbs will likely become relationships between tables
  • Details about a noun become attributes, so columns in that table

Pulling out the nouns (and dropping duplicates) gets us users, channels, videos, comments and playlists. Likes and dislikes are a bit more abstract, but they describe a reaction, so I'd store them as reactions.

If you're unsure about one, put a mark by it and circle back. The one I'd circle is "a comment can be a reply". Is a reply a noun that deserves its own table? A reply doesn't have any extra information compared to a comment, so for me it's just an attribute on the comment (which comment it's replying to, or nothing). That one's a little confusing at first because it IS a verb, it's just a relationship between a comment and another comment in the same table.

Then the verbs. Each one is a relationship:

  • user creates channel
  • channel uploads video
  • user subscribes to channel
  • user comments on video
  • comment replies to comment
  • user creates playlist
  • video added to playlist
  • user reacts to video

Then it comes down to knowing which type each relationship is, one-to-one, one-to-many or many-to-many.

Relationships

Relationships are one of the most important topics here. Normalization and a lot of the other popular design stuff is built on them, so if you get these, the normalization part later is easy.

There are three: one-to-one, one-to-many and many-to-many. You might see them written as 1:1, 1:M and M:N.

One-to-one relationship

A one-to-one is when two entities are exclusive to each other. And this is often a design choice, not a right-or-wrong answer. I get a lot of comments asking "should it be this way or that way?" and the answer usually comes down to what the business wants.

From our list, say a user has at most one channel, and a channel is owned by at most one user. That's a classic one-to-one, and whether it's correct comes down to the business choice, like do you want users to be able to make multiple channels, or a channel to be owned by multiple users? A lot of platforms do allow that, and then it's not a one-to-one anymore.

There are two ways to design a one-to-one:

  1. Just use a column. If the values are coupled, put the channel handle right on the user row.
  2. Use a separate table connected with a foreign key.

The first way is the default I'd reach for. Something like this:

email created_at age hashed_pw channel_handle
caleb@calebcurry.com ... ... ... @codebreakthrough

So why ever split it out? Two main reasons. One is if the thing has its own attributes, so a bunch of data that's really about the channel and not the user (that's a transitive dependency, more on that in the normalization section). The other is data separation. I see this a lot where a user's personal info like address or other sensitive data lives in a completely separate table, both for isolation and to thin out the main row so you only grab what's needed for the user account. It's still a one-to-one, it's just split across two tables.

Across two tables, the foreign key could go on the user:

users

id channel_id
32 1

channels

id handle
1 codebreakthrough

One-to-many relationship

A one-to-many is a small change from a one-to-one across two tables, which is a good reason to think about which direction the foreign key points.

With a one-to-one across tables the key can point either way since the two are exclusive. But if you might want one-to-many later, put the foreign key in the table that would become the "many" side. So instead of the user pointing at the channel, the channel points back at the user:

users

id email
32 caleb@calebcurry.com

channels

id handle user_id
1 codebreakthrough 32

user_id is the foreign key. To keep this a one-to-one, you make that foreign key unique. Then if I try to add another channel with user_id 32, the database blocks it:

id handle user_id allowed?
1 codebreakthrough 32 yes
2 codebreak 32 no, 32 is already used

To switch to one-to-many, all you do is remove the unique constraint. Now user 32 can own both codebreakthrough and codebreak (codebreakthrough is entirely too long, codebreak I kinda like because my code is always broken).

So the only difference between a one-to-one and a one-to-many across two tables is whether that foreign key is unique:

1:1   FK is UNIQUE
1:M   FK is not UNIQUE

Here's the one-to-one version in Postgres:

SQL
CREATE TABLE users (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL UNIQUE
);

CREATE TABLE channels (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    handle text NOT NULL,
    user_id bigint NOT NULL UNIQUE REFERENCES users (id)
);

And the one-to-many version of channels, which is the same thing without UNIQUE:

SQL
CREATE TABLE channels (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    handle text NOT NULL,
    user_id bigint NOT NULL REFERENCES users (id)
);

Many-to-many relationships

Now what if a user can create multiple channels AND a channel can be owned by multiple users? Say James (user 47) is sharing the codebreak channel with me.

The first thing people often try is adding another row to channels for the same channel pointing at James:

id handle user_id
1 codebreakthrough 32
2 codebreak 32
3 codebreak 47

That's wrong and bad. You now have repeating data, and the same channel has two different IDs.

The fix is a third table, often called a junction table (or intermediary table). It sits between the two other tables and splits the many-to-many in to two one-to-many relationships.

For the name, the convention is kind of stupid but you'll usually just see the two names combined, like user_channels. I make one singular and one plural, but it varies, even between database systems. What's pretty common is underscores for multiple words, because SQL usually lowercases anything you type unless you put quotes around it.

The channel no longer stores an owner, that all moves into the junction table:

users

id email
32 caleb@calebcurry.com
47 james@...

channels

id handle
1 codebreakthrough
2 codebreak

user_channels

user_id channel_id
32 2
47 2
32 1

So user 32 owns channel 1, and channel 2 is shared by users 32 and 47. Each channel is only in channels once.

The cool thing is a junction table is the perfect home for anything that describes the relationship itself. Realistically you probably don't want James to be a full co-owner. Maybe he's an editor, or he can manage comments but can't delete stuff. That tier describes the connection between that user and that channel, so it goes here:

user_id channel_id role
32 2 owner
47 2 manager
32 1 owner

You could add timestamps for when the connection was made too.

Notice the IDs can repeat in each column here, unlike in users or channels. What can't repeat is the combination. If I added 32, 2, manager I'd be both the owner and the manager of the same channel, and now the data doesn't make sense. So there are really three constraints on this table: two foreign keys and a unique constraint across the pair.

SQL
CREATE TABLE user_channels (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES users (id),
    channel_id bigint NOT NULL REFERENCES channels (id),
    role text NOT NULL,
    UNIQUE (user_id, channel_id)
);

Once your intuition gets stronger you'll just start to notice many-to-many relationships. You ask the question in both directions. Take videos and playlists:

  • Can a video be added to many playlists? Yes.
  • Can a playlist have many videos? Yes.

If you get two yeses it's many-to-many, and if you only get one yes it's one-to-many, where the many side is the child, the table holding the foreign key.

So we get playlists, videos and a junction table. I don't like video_playlists, I like to word it left to right, so it's playlist_videos.

That table starts out purely as a way to connect the two, but as you add attributes it grows up into its own entity. A good example is the position of a video in the playlist:

playlist_videos

playlist_id video_id position
1 1 1
1 2 2
3 4 1
3 1 2
3 5 3

Playlist 1 has two videos and playlist 3 has three. The downside is if you move videos around you have to update the positions across that playlist, but it's a simple design and a small trade-off. There are other approaches to ordering, this is just one of the simplest to wrap your mind around in my opinion.

You might also see the junction table skipped entirely, with the playlist storing an array of video IDs (and the position in the array is the order):

playlist_id video_ids
1 [1, 2]
3 [4, 1, 5]

That's denormalizing, going to fewer tables. It's simpler and probably faster with fewer joins, but there's no foreign key, so you lose referential integrity unless you enforce it some other way like triggers. The three-table structure uses native foreign keys and is probably the proper way to do it. I'm not saying use the array, just that you'll see it.

Going back through the rest of the verbs from the start:

relationship type table
user creates channel 1:M foreign key on channels
channel uploads video 1:M foreign key on videos
user subscribes to channel M:N subscriptions
user comments on video M:N comments
comment replies to comment 1:M to itself a column on comments
user creates playlist 1:M foreign key on playlists
video added to playlist M:N playlist_videos
user likes or dislikes video M:N reactions

A video belongs to one channel. Connecting the video to the channel instead of the user also plays nicer with shared channels. You could think about collaborations, but by default I'd do one-to-many. Subscribing is a different connection than a user creating a channel, so that one's separate.

For many-to-many you can use the default combined name, or give the junction table a name that describes the relationship. A user commenting on a video doesn't need to be user_videos, it can just be comments.

So here's V1 of our design, going with one owner per channel (add user_channels from above if you want shared channels). If you were building something like YouTube for real there'd be way more than this.

SQL
CREATE TABLE users (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL UNIQUE
);

CREATE TABLE channels (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    handle text NOT NULL UNIQUE,
    user_id bigint NOT NULL REFERENCES users (id)
);

CREATE TABLE videos (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title text NOT NULL,
    channel_id bigint NOT NULL REFERENCES channels (id)
);

CREATE TABLE comments (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES users (id),
    video_id bigint NOT NULL REFERENCES videos (id),
    reply_to bigint REFERENCES comments (id),
    body text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE subscriptions (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES users (id),
    channel_id bigint NOT NULL REFERENCES channels (id),
    UNIQUE (user_id, channel_id)
);

CREATE TABLE reactions (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES users (id),
    video_id bigint NOT NULL REFERENCES videos (id),
    kind text NOT NULL CHECK (kind IN ('like', 'dislike')),
    UNIQUE (user_id, video_id)
);

CREATE TABLE playlists (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL,
    user_id bigint NOT NULL REFERENCES users (id)
);

CREATE TABLE playlist_videos (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    playlist_id bigint NOT NULL REFERENCES playlists (id),
    video_id bigint NOT NULL REFERENCES videos (id),
    position integer NOT NULL,
    UNIQUE (playlist_id, video_id)
);

Using three keys

If you want to get a little freaky, relationships can go three ways or more.

Back to channels managed by multiple users. Instead of storing the permission level inline as a string or an enum, the third column can reference another table:

permissions

id name
1 owner
2 admin
3 editor

user_channels

user_id channel_id permission_id
1 1 2

So user 1 is an admin of channel 1.

Here you can put a unique constraint across all three columns (or make the three of them the primary key, more on keys in a bit, I usually still give junction tables their own ID):

SQL
CREATE TABLE permissions (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL UNIQUE
);

CREATE TABLE user_channels (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES users (id),
    channel_id bigint NOT NULL REFERENCES channels (id),
    permission_id bigint NOT NULL REFERENCES permissions (id),
    UNIQUE (user_id, channel_id, permission_id)
);

Be aware of what that allows though. With the unique across all three, I could also add 1, 1, 3, so I'm an admin AND an editor of that channel:

user_id channel_id permission_id
1 1 2
1 1 3

That works if permissions aren't exclusive, like a manager handles comments and an editor handles videos and you can have both.

If you don't want someone to have more than one permission on a channel, take permission_id out of the unique constraint. It's still a foreign key, but now user_id, channel_id can't repeat, so there's only one permission per user per channel:

SQL
UNIQUE (user_id, channel_id)

This is to build some intuition for how changing what's in a constraint changes what the database allows.

Lookup table

That permissions table is called a lookup table. It's basically a universal way to make an enum where you choose from a few possible values.

The nice part is updating it. If we want to rename editor to content manager, we change one row:

SQL
UPDATE permissions SET name = 'content manager' WHERE name = 'editor';

We don't have to change a string in 100 different places, and we don't have to change a type like we would with an enum. Adding an option is just adding a row.

So lookup tables are one-to-many relationships used to reference some value, and you can add more columns describing that value if you need to.

Primary keys and foreign keys

A key is how we tell one row apart from another, there needs to be something unique about a row so we can talk about that row specifically.

Every table needs a primary key. Setting a column as the primary key makes it indexed (fast lookups by that key) and unique. The three big rules:

  • it's unique, you can't have two comments with ID 300
  • it never changes, comment 300 shouldn't become comment 305
  • it can't be null (null just means missing a value), every row has one

A foreign key references a value in another table, usually that table's primary key. The primary key rules don't apply to foreign keys. A foreign key column doesn't have to be unique, it can change and it can be null. It's there to make the connection and to define what happens if you try to break that connection.

Don't let all the terminology coming up overwhelm you. Every row has a key, and if you want to reference a row from another table, you use a foreign key.

Primary key

The IDs we've been using are surrogate keys. They're made up and have no meaning in the real world, unlike a social security number or an email. They're for the database only, and we don't expose them to users.

The other kind is a natural key, a value that actually means something, like a username or email.

So which do you choose? I think it's a good idea to design your tables so they COULD have a natural key, but I still prefer surrogate keys. That's my personal opinion. I don't want real-world data tangled up with the keys that make connections in the database, so I keep the two separate and give everything an ID, even junction tables. For a junction table I'll give it its own ID so the connection can be referenced with a single column, and mark the combination as unique instead of making it the key:

id first key second key
1 1 2
2 3 4
3 1 7

The first column is the key, the other two together are UNIQUE.

You can make multiple columns the key though. That's a composite key or compound key. Technically a compound key is made of columns that are each keys themselves, and a composite key is made of multiple columns that don't all have to be keys. That's splitting hairs, it's the same idea.

Example: a comments table. If (user_id, video_id) was the key, you could only comment once on a video. Add the timestamp, (user_id, video_id, ts), and you can comment again as long as it's not the exact same moment. That's a composite natural key. But composite keys get complicated pretty quick in my opinion, especially when another table has to reference them by multiple columns, so I'd rather give the comment its own ID.

Candidate key

If something could have worked as the key, like that (user_id, video_id, ts) combo, and you downgrade it to a unique constraint, that's a candidate key (or alternate key). Basically something you could have chosen as the key.

SQL
CREATE TABLE comments (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES users (id),
    video_id bigint NOT NULL REFERENCES videos (id),
    ts timestamptz NOT NULL DEFAULT now(),
    UNIQUE (user_id, video_id, ts)
);

It's ideal for a table to have some candidate key even when you use surrogate keys. It's not a hard rule, but it goes back to data integrity, we don't want a surrogate ID and then let the rest of the row be whatever it wants.

You can judge a candidate key by how unique it actually forces the data to be. The comment one is pretty weak. If someone double clicks, or the client sends the request twice, or there's a glitch on the backend, you get two identical comments with slightly different timestamps, and it's hard to tell if they meant to post it twice. Comments just don't have a strong natural key. Something like daily stats for a video has a much stronger one, since the video and the day are naturally unique together.

So to sum up everything I just said in like five words, use a surrogate key, please.

Auto-incremented ID vs GUID

OK, so you're using a surrogate key, but it's not that simple. You can use an auto-incremented ID (counting 1, 2, 3, 4 up for eternity) or a UUID/GUID (universally or globally unique identifier), which is basically a random ID instead of counting up.

This goes back to the architecture stuff from the beginning. If you have a centralized database that everything points to and it can auto increment, that's probably what I'd go with. Globally unique IDs are more common in decentralized setups with multiple database nodes. If every node auto increments, you'd end up with the same ID reused across nodes, and then you need a centralized ID distributor and all this crazy system design stuff. A simple fix is to use a UUID.

You can generate it in your code when you insert the row, or have the database generate it. In Postgres, pick one of these:

SQL
-- auto-incremented
CREATE TABLE users (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL UNIQUE
);

-- UUID generated by the database
CREATE TABLE users (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    email text NOT NULL UNIQUE
);

gen_random_uuid() is built into Postgres 13 and up, see the UUID functions docs.

Foreign key

The lookup table from earlier is a great example. We have permissions and the junction table (I call it channel_users on the board at this point, it's the same idea as user_channels), with a row like user 1, channel 3, permission 2:

channel_users

id user_id channel_id permission_id
1 1 3 2

The foreign key says that 2 has to exist in the permissions table, so the column is defined as referencing permissions and its ID:

SQL
permission_id bigint REFERENCES permissions (id)

That junction table actually has three foreign keys pointing at three different tables, plus its own surrogate ID as the primary key.

The rules for a foreign key are pretty simple:

  • it has to reference a unique column (the destination has to be unique)
  • the foreign key value itself does NOT have to be unique, there are going to be a lot of admins
  • it can be null if you allow it (this person has no permissions)
  • it can change (promote them to owner)

There are two configurations on a foreign key to know about, ON UPDATE and ON DELETE. ON UPDATE isn't super relevant, because 99 out of 100 times the foreign key references a primary key and primary keys shouldn't change.

ON DELETE is the one to care about. The referenced row is the parent and the row with the foreign key is the child, and this decides what happens to the child when you delete the parent. The exact names vary by database, but the list looks like this:

  • NO ACTION - the default. Errors out and won't let you delete the parent. Probably a good safe default.
  • RESTRICT - also errors out. The difference from NO ACTION only shows up in a transaction: NO ACTION lets you get things back to a valid state before the transaction finishes (like deleting the row and recreating one with the same ID), RESTRICT errors right away. In some databases these two are exactly the same, so check yours.
  • CASCADE - deleting the parent deletes the children too. It feels like it makes sense a lot of the time, but it's pretty dangerous because one delete can have side effects you didn't realize. It does make sense for something like deleting a video and having its comments go with it, or deleting a user account and their settings.
  • SET NULL - breaks the connection and leaves an orphaned row, a child with no parent, which is a little depressing. Safer, since nothing downstream gets deleted. The column has to be nullable for this to work.
  • SET DEFAULT - same idea, but sets it to the column's default instead of null.

💡 Tip[!tip]
In Postgres specifically, NO ACTION is checked at the end of each statement, and only waits until the transaction commits if you declare the foreign key DEFERRABLE and defer it. See the Postgres constraints docs.

Most of the time I'd recommend NO ACTION or SET NULL, that gets you most of what you need without the risk of CASCADE. If the column needs a value, use SET DEFAULT instead of SET NULL.

In Postgres it goes right on the reference:

SQL
CREATE TABLE comments (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    video_id bigint NOT NULL REFERENCES videos (id) ON DELETE CASCADE,
    user_id bigint REFERENCES users (id) ON DELETE SET NULL,
    body text NOT NULL
);

Those same docs go through every option if you want the exact behavior.

One more thing, I don't believe foreign key columns are indexed by default (in Postgres they aren't, though a primary key or unique constraint gets an index automatically), so if you query by a foreign key a lot you might want to add one yourself:

SQL
CREATE INDEX ON comments (video_id);

Learn the details of your specific RDBMS.

When should you delete data?

This brings up a better question, when should you delete data at all? It's worth doing some dedicated research on.

A lot of the time you'll want a soft delete. If someone deletes their account, the row gets a flag saying it's deleted but it still exists, and anything that stays in that state for 30 or 90 days gets deleted for real. One way to store that flag is a nullable timestamp, so you also know when it happened:

SQL
ALTER TABLE users ADD COLUMN deleted_at timestamptz;

That lets your app be more aggressive with deletes without risking data loss or having to restore a backup.

Also think about the legal side. If you serve users somewhere data privacy is taken seriously, you might be required to actually delete the data and not just flag it.

Normalization

Normalization is the process of breaking single tables up in to multiple tables to apply certain design rules that protect data integrity. A lot of people get tripped up here because they study it before understanding everything above. If you've followed along so far, this part is mostly rewording stuff we already did.

Let's start with an awful table that has everything in one place:

videos

video tags channel owner_email name
Git in 1hr git, github, version control codebreakthrough caleb@email.com Caleb
Docker Crash Course docker, docker compose codebreakthrough caleb@email.com Caleb

Git in one hour is coming soon maybe, might want to subscribe, never know.

Issues:

  • Every video duplicates the channel, email and name. Change my name and you either update it everywhere or end up with conflicting values.
  • Tags has multiple values in one field, so searching for docker compose is a pain.
  • Changing the channel owner, or having multiple owners, means changing every row or turning it into an array.

Those map to the classic anomalies:

  • update anomaly - you change a value in one place and it doesn't propagate, so the data drifts
  • insert anomaly - you can't add a new channel without also adding a video and its tags, kind of a catch 22
  • delete anomaly - delete these two videos and you just deleted everything we know about the channel too

This is the extreme version, but smaller versions of these show up any time a database isn't normalized.

Normal forms

The normal forms are the steps in normalization. There are a bunch of them, but I only care about the first three. They build on each other: to be in second normal form you have to be in first, and to be in third you have to be in second.

First normal form (1NF)

1NF is about values being atomic. I know it's not scientifically accurate, but the idea is an atom is the smallest unit, so you don't put multiple values in one cell.

The first fix people think of is duplicating the row, one with docker and one with docker compose:

video tags channel
Docker Crash Course docker codebreakthrough
Docker Crash Course docker compose codebreakthrough

That's not right either, because now two rows describe the same video. Basically, we want unique rows, each one identifiable with an ID.

The rule is any time something breaks this, you introduce a new table. So tags gets its own table. This is also where I'd pull out obvious duplicate values like the channel:

videos

video_id name channel_id
1 Git in 1hr 1
2 Docker 1

tags

tag_id video_id name
1 1 git
2 1 github
3 1 version control
4 2 docker
5 2 docker compose

channels

channel_id channel_name email name
1 codebreakthrough caleb@email.com Caleb

As I've mentioned probably a hundred times, I gave the tags table its own surrogate ID too.

Second normal form (2NF)

2NF deals with partial dependencies, which is when an attribute depends on only part of the key.

You might be thinking, if everything has a surrogate key, how can anything depend on half of it? Go off of what would be a good natural composite key, so look at the unique constraints. This comes up a lot in junction tables since that's where you usually have two keys. Here that's the video and the tag name.

There are a few things we might add to a tag, like a color or a description for a tag landing page. Let's go with a category so they can be grouped, all of these would be tech:

tags

tag_id video_id name category
1 1 git tech
2 1 github tech
3 1 version control tech
4 2 docker tech
5 2 docker compose tech

That's a 2NF violation. The table is about which tags are on which video, but category describes the tag and has nothing to do with the video. It depends on the tag, not the video.

The fix is to rename this one to video_tags, break the category off into its own table, and replace it with a foreign key:

tag_categories

tag_category_id name desc
1 tech nerd stuff

video_tags

tag_id video_id name category
1 1 git 1
2 1 github 1
3 1 version control 1
4 2 docker 1
5 2 docker compose 1

That ID repeats, but it's tied to one row, so changing the category means changing one place instead of five strings.

Third normal form (3NF)

3NF deals with transitive dependencies. That's a chain, where a column depends on another column which depends on the primary key.

In channels, the email and name depend on who the owner is, not really on the channel. Look at a different channel and the email changes, and the name changes with it, so it hops through multiple columns. Find that chain and split it off:

users

user_id email name
73 caleb@email.com Caleb

channels

channel_id name user_id
1 codebreakthrough 73

user_id is a foreign key to users, and we're assuming one owner for now. No more transitive dependencies.

There's still one more design flaw. Since each tag row is tied to a video, adding git again creates a new git row, and nothing stops that one from getting a different category:

tag_id video_id name category
1 1 git 1
6 2 git 2

Every tag applied to a video gets its own category instead of the category belonging to the tag.

The fix is splitting again (and this is why you start with one table and end up with 750). Have a dedicated tags table with each tag once and its category, and a video_tags junction table with the video and tag IDs:

tags

id name category
1 git 1
2 github 1
3 version control 1
4 docker 1
5 docker compose 1

video_tags

id video_id tag_id
1 1 1
2 1 2
3 1 3
4 2 4
5 2 5

Now git always has the same category, and videos just reference it by ID. Here's that final design in Postgres:

SQL
CREATE TABLE users (
    user_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL UNIQUE,
    name text NOT NULL
);

CREATE TABLE channels (
    channel_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL,
    user_id bigint NOT NULL REFERENCES users (user_id)
);

CREATE TABLE videos (
    video_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL,
    channel_id bigint NOT NULL REFERENCES channels (channel_id)
);

CREATE TABLE tag_categories (
    tag_category_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL UNIQUE,
    description text
);

CREATE TABLE tags (
    tag_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL UNIQUE,
    tag_category_id bigint REFERENCES tag_categories (tag_category_id)
);

CREATE TABLE video_tags (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    video_id bigint NOT NULL REFERENCES videos (video_id),
    tag_id bigint NOT NULL REFERENCES tags (tag_id),
    UNIQUE (video_id, tag_id)
);

Normalization is kind of just a game of making sure there are no integrity issues, and it's a spectrum. Sometimes you'll choose to denormalize for a trade-off, and if you're creating a bunch of tables without much benefit you can stop early. That's basically what we did, there are normal forms after 3NF, but that's where you get into a lot of normalization for minimal benefit, so I just think about the first three.

What's next?

Most of design is breaking things out into more tables. Getting that data back together is what joins are for, and you do that in SQL. Turning these concepts (foreign keys, unique constraints, data types, views, indexes) into real things in a database is all SQL too, and there's enough there that it deserves a dedicated video.

So from here, check out my SQL course to keep going. If you want more on the system design side of databases, like the CAP theorem and consistent hashing, check out my system design playlist and my backend engineering playlist.

Powered by Course Catalyst