in

Introduction to Databases

Relational vs Non-Relational

Let us take the example of keeping a database of users and their comments. What are the differences between a Relational and a Non-Relational database in this scenario

Relational (SQL)

We would start with a table for the users. All new users must follow this same format.

– >
USERS
idnameagecity
1Nick56Denver
2Sarah34NYC
3Dave15Paris

and a comments table

COMMENTS
idcomment
1“Great post, thanks.”
2“Dogs > Cats”
3“I strongly disagree.”
4“Happy Birthday friend!”

There is currently no information that is linking the users to the comments. Who said what? To join the two together we need to have a Join Table.

JOIN TABLE
userIdcommentId
13
12
31
44

The key takeaway here, is that everything is tabular. Tables must be defined ahead of time and are not flexible. If I wanted to add a new piece of information for the users table, like birthday, I could add a column, but I have to put in a value for every single user, even if I don’t know the correct information. This will result in a lot of null values in the database.

USERS
idnameagecitybirthday
1Nick56Denvernull
2Sarah34NYC8/24/85
3Dave15Parisnull

Non-Relational (NoSQL)

In Non-Relational tables we don’t have to define patterns ahead of time. They are much more flexible. There are no tables, and therefore no tabular structure, and data can be nested. It is not “flat”.

Non-Relational databases use a format called BSON (Binary JavaScript Object Notation).

// BSON Data Structure
{
    name: "Dave",
    age: 25,
    city: "Detroit",
    comments: [
        {text: "I'm from Motor City."},
        {text: "I miss the pizza in Chicago."}
    ]
}

Note that the comments are nested inside of the data.

Which Is Better?

One is not better than the other. Relational databases are more common, and will work better in most situations. But there are some situations where a non-relational database will be advantageous.

API category header

Express + API: Dynamic API Requests

Introduction to MongoDB