Types of Database

A database type is the basic way a database arranges its data. Relational keeps tables that point at each other by id (the unique number of each row), is…

In the previous lesson and in the SQL track, data was always kept in tables. But not every database keeps data in tables. Picture five clerks recording the same order, each in their own way:

The data is the same, but each clerk answers different questions easily. Databases are like that too. The basic way a database arranges its data is its database type. The five clerks are five database types, in this order: relational, document, key-value, graph and time-series.

One order, five shapes

We use Sunset Coffee's order #1: Budi buys 2 Milk Coffee ($4.50) and 1 Toast ($5.00). There are also order #2 (Budi, 1 Palm Sugar Milk Coffee) and #3 (Siti, 1 Milk Coffee and 1 Milk Tea). The Lab on this page stores those three orders in the first four shapes (relational to graph), and you can ask each shape the same thing.

Relational: tables that point at each other

A relational database works like the first clerk: it keeps data in tables of rows and columns, and the tables connect through ids. Its language is SQL. Examples are PostgreSQL, MySQL and SQLite. Order #1 is spread over four tables: customers, orders, order_items (one row per product in an order, covered in the Cardinality & Relationships lesson) and products. To read it whole, the four tables are combined with JOIN:

SELECT c.name, p.name AS product, oi.qty, p.price
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.id = 1
ORDER BY oi.product_id;
name product qty price
Budi Milk Coffee 2 450
Budi Toast 1 500

o, c, oi and p are short names for those four tables, and AS product gives the column p.name the name product.

Document: one folder holding everything

A document database works like the second clerk: it keeps each item as one document, with everything inside. A document is shaped like a JSON object (pairs of names and values inside curly brackets). Examples are MongoDB, Firestore and CouchDB. In MongoDB, order #1 is one document:

db.orders.findOne({ _id: 1 })
// {
//   _id: 1,
//   customer: { _id: 1, name: 'Budi' },
//   items: [
//     { product: 'Milk Coffee', price: 450, qty: 2 },
//     { product: 'Toast', price: 500, qty: 1 }
//   ]
// }

findOne({ _id: 1 }) gets the document whose _id is 1. The // lines below it show what is inside that document.

Key-value: numbered lockers

A key-value store works like the third clerk: it keeps pairs of a key (the number or name on the locker door) and a value (what's inside). Examples are Redis and Memcached. In redis-cli (the program for typing commands to Redis):

127.0.0.1:6379> SET session:7f3a "1"
OK
127.0.0.1:6379> GET session:7f3a
"1"

Graph: points and lines

A graph database works like the fourth clerk. The photos are nodes (points: Budi, order #1, Milk Coffee), and the threads are edges (labelled lines). For example, the edge PLACED goes from Budi to order #1, and the edge CONTAINS goes from order #1 to Milk Coffee. An example is Neo4j, with its query language Cypher. This query finds the other products bought together with Milk Coffee:

MATCH (:Product {name: 'Milk Coffee'})<-[:CONTAINS]-(:Order)-[:CONTAINS]->(other:Product)
RETURN DISTINCT other.name

In Cypher, ( ) is a node and -[:CONTAINS]-> is an edge with its direction. The result is Toast and Milk Tea. The query just follows lines: from the Milk Coffee node back to the orders that contain Milk Coffee (#1 and #3), then forward to the other products in those two orders. So for a feature like "people who buy Milk Coffee also buy...", a graph database answers most easily. A relational database can do it too, but the order_items table has to be JOINed to itself. Every extra line to follow ("a friend of a friend of a friend") means one more JOIN. Graph databases fit social networks (friendships) and recommendations.

Time-series: numbers lined up by time

A time-series database works like the fifth clerk: it keeps values recorded at regular intervals, each with its time. Examples are InfluxDB, TimescaleDB (an add-on for PostgreSQL) and Prometheus. Sunset Coffee records its coffee machine's temperature every minute:

time temperature
08:00 92.5
08:01 93.1
08:02 91.8

This temperature data keeps growing, is almost never changed, and is asked about by time range ("the average temperature per hour today"). A time-series database is built for data like this, so it fits monitoring (watching) servers, IoT sensors (devices connected to the internet), and analytics.

Which one to pick

Need Type
caching, session key-value
social network, recommendations graph
monitoring, IoT time-series
CMS, catalogue document
the rest: online shops, banks, data with many relationships relational

Real apps often use more than one type. Sunset Coffee keeps orders in PostgreSQL (relational) and login sessions in Redis (key-value). When in doubt, start with relational, because it answers almost every question well enough.

One more type you will meet more and more: the vector database. Each row stores a list of numbers (an embedding) that stands for the meaning of a text or a picture, and the question is "which rows are closest in meaning?". Vector databases are used for search by meaning and for AI chatbots. You do not have to install a new database: the pgvector extension (an add-on) lets PostgreSQL work as a vector database:

CREATE EXTENSION vector;
CREATE TABLE products (id BIGINT PRIMARY KEY, name TEXT, embedding vector(3));
-- the two products closest in meaning to [0.9, 0.1, 0.2]
SELECT name FROM products ORDER BY embedding <=> '[0.9, 0.1, 0.2]' LIMIT 2;

<=> calculates the cosine distance: the smaller it is, the closer the meaning. Say the table holds Milk Coffee [0.9, 0.1, 0.1], Palm Sugar Milk Coffee [0.8, 0.2, 0.3], Milk Tea [0.1, 0.9, 0.1] and Toast [0.1, 0.1, 0.9]. Then the result is Milk Coffee, then Palm Sugar Milk Coffee. Real embeddings hold hundreds to thousands of numbers, not 3. Laravel 13 (a PHP framework) has $table->vector('embedding', 1536) and whereVectorSimilarTo() for this column.

⚠️ Picking the wrong type, or using it wrong

TL;DR: A database type is the basic way a database arranges its data. Relational keeps tables that point at each other by id (the unique number of each row), is asked with SQL and combines tables with JOIN. It is strong at relationships and transactions, that is, several changes that all succeed or all roll back (online shops, banks). Document keeps one whole document per item, whose shape may vary (catalogues, a CMS for website content). Key-value keeps key (name) and value (content) pairs in memory: very fast, but it can only find data by key (caching computed results, login sessions). Graph keeps nodes (points) and edges (lines between points), good at following layered connections such as friends of friends (social networks, recommendations). Time-series keeps numbers over time (server monitoring, IoT sensors). When in doubt, start with relational.

⚡ Relational: tables that point at each other

Write:

SELECT c.name, p.name AS product, oi.qty, p.price
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.id = 1
ORDER BY oi.product_id;

Meaning: A relational database keeps data in tables of rows and columns that connect through ids (the unique number of each row), and is asked with SQL. Order #1, spread over four tables, is read whole with JOIN. o, c, oi and p are short names for those four tables. Relational is strong at relationships and transactions (several changes that all succeed or all roll back), so it fits online shops and banks.

⚡ Key-value and document

Write:

127.0.0.1:6379> SET session:7f3a "1"
OK
127.0.0.1:6379> GET session:7f3a
"1"
Guess first: Redis, a key-value store, keeps each piece of data under one key (a name), like session:7f3a. With only GET, can Redis answer "which orders contain Milk Coffee?"

No. GET only finds data by key. So every key has to be read one by one, and then your app checks what's inside.

Meaning: SET stores the value (the content) "1" under the key session:7f3a, and GET reads it back. Key-value keeps key and value pairs in memory, very fast for caching (keeping computed results to use again) and login sessions. Document keeps one whole document per item, for example one order together with its customer and products. Each document's shape may vary, so document fits catalogues and a CMS (a system that manages website content).

⚡ Graph, time-series, then pick

Meaning: Graph keeps nodes (points, such as a customer or a product) and edges (lines between nodes), good for social networks and recommendations. Time-series keeps numbers over time, for server monitoring and IoT sensors. When in doubt, start with relational.

In the exercise, return the database type as exact lowercase text: "key-value" and "time-series" have a hyphen.

What you will learn