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
id name age city
1 Nick 56 Denver
2 Sarah 34 NYC
3 Dave 15 Paris

and a comments table

COMMENTS
id comment
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
userId commentId
1 3
1 2
3 1
4 4

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
id name age city birthday
1 Nick 56 Denver null
2 Sarah 34 NYC 8/24/85
3 Dave 15 Paris null

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