C.W.K.
Stream
Lesson 03 of 10 · published

Relational vs Document vs Key-Value

~14 min · foundations, models

Level 0Schema Seedling
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Three ways to organise your closet

Relational is a dresser with labelled drawers: socks here, shirts there, every drawer cross-referenced so you can answer "which shirts go with which trousers." Document is a row of boxes, each holding one complete outfit (shirt, trousers, socks together) — fast to grab, slow to answer "show me every red shirt anyone owns." Key-Value is a row of hooks: each hook has a label, one item, and zero structure beyond that.

When each model wins

Relational wins when relationships matter and you want the database to enforce them. Document wins when the shape of each record genuinely varies and you query by document, not by relationship. Key-Value wins when you need raw speed for "give me X by exact key" and nothing else.

The PostgreSQL twist

PostgreSQL is the only major database that does all three credibly. Relational is the default. JSONB columns give you document-style storage with proper indexing. hstore gives you key-value. The pragmatic answer to "do I need MongoDB?" is almost always "no — add a JSONB column."

Code

Relational: cross-referenced tables·sql
SELECT customers.name, orders.total
FROM   customers
JOIN   orders ON orders.customer_id = customers.id
WHERE  orders.total > 100;
Document: same data inside Postgres JSONB·sql
CREATE TABLE customer_orders (
    id        INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer  TEXT NOT NULL,
    payload   JSONB NOT NULL
);

INSERT INTO customer_orders (customer, payload) VALUES
('Alice', '{"orders":[{"product":"Widget","total":150},
                     {"product":"Gadget","total":45}]}');

-- Query inside the JSON document
SELECT customer,
       jsonb_array_elements(payload->'orders') ->> 'product' AS product
FROM   customer_orders;
Key-value: Redis-style lookup·text
SET   user:42:session  "abc123"
GET   user:42:session
"abc123"

External links

Exercise

Write the same 'find all orders over $100 for customer Alice' query in three forms: pure relational (two tables + JOIN), JSONB inside a single table, and pseudo key-value (Redis-style commands). Compare how readable each is and which one you'd reach for first.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.