Types of databases: SQL, key-value, document, wide-column, graph and time-series explained

There is no best database, only the right one for a job. Learn the six main database types, what each one is good and bad at, and a simple way to choose: start with PostgreSQL and Redis, and add others only when an access pattern demands it.

A shelving unit with six labelled compartments, one per database type, under a sign that asks "Where does this data live?". Relational holds a table with linked columns. Key-value holds numbered lockers and a key. Document holds a folder of JSON papers. Wide-column holds long rows labelled chat:A, chat:B and chat:C, sorted by time. Graph holds a pinboard of notes joined by red string. Time-series holds a tape of readings drawn as a rising line.
Fig. 1 — Different data needs a different home. The skill is matching each kind of data to the store built for how you use it.

You wouldn’t keep your clothes in the garage or your car in the bedroom. Each thing in a house has a place built for how you use it. Data is the same.

Look at the data inside one online shop:

  • Orders and payments must never be half-saved. Money is involved.
  • Shopping carts must load instantly, and can disappear after a while.
  • Product details differ by product: a laptop has RAM and screen size, a shirt has size and colour.
  • Server metrics arrive every second, forever, and are read by time range.
  • “Customers who bought this also bought…” is a question about connections.

A team that puts all of this into one PostgreSQL database will hit trouble. Session lookups compete with order writes. Heavy analytics reports slow down checkout. “Friends of friends” queries need join after join. And the single database becomes a bottleneck for every service at once.

No single database is perfect for every one of these needs. That’s why there are different types. This article opens the Data storage & data modeling thread: where your data lives, and how you shape it.

The six database types at a glance

Six cards, one per database type. Relational: tables with rows and columns, linked by keys; PostgreSQL, MySQL; for orders, payments, accounts. Key-value: a key points to a value, like a giant hash map; Redis, DynamoDB; for sessions, caches, counters. Document: JSON-like documents with nested data; MongoDB; for catalogs and profiles. Wide-column: rows grouped by a partition key and sorted by time; Cassandra, HBase; for huge write volumes like message history. Graph: nodes joined by edges; Neo4j; for social networks, recommendations, fraud. Time-series: timestamp plus tags plus values; InfluxDB, TimescaleDB; for metrics and sensor data.
Six shapes of data, six kinds of store. Each one is fast at the access pattern it was built for.
Type Data looks like Great at Weak at Examples
Relational Tables, rows, keys Transactions, joins, data integrity Scaling writes across machines PostgreSQL, MySQL
Key-value key → value Sub-millisecond lookups, expiry (TTL) Any query that isn’t “by key” Redis, DynamoDB
Document JSON documents Flexible, nested data Joins, cross-document consistency MongoDB
Wide-column Rows grouped by partition key Huge write volume, time-ordered reads Flexible queries, joins Cassandra, HBase
Graph Nodes and edges Multi-hop relationship queries Simple CRUD, horizontal scaling Neo4j
Time-series Timestamp + tags + values Fast writes, time ranges, roll-ups General-purpose data InfluxDB, TimescaleDB

Let’s look at each one: what it is, when it shines, and what it costs you.

1. Relational databases (SQL)

Data lives in tables with a fixed schema. Tables link to each other with keys, and the database enforces the rules: no order for a user who doesn’t exist, no balance below zero.

CREATE TABLE users (
    user_id    BIGINT PRIMARY KEY,
    email      VARCHAR(255) UNIQUE NOT NULL
);

CREATE TABLE orders (
    order_id     BIGINT PRIMARY KEY,
    user_id      BIGINT NOT NULL REFERENCES users(user_id),  -- no orphan orders
    total_amount DECIMAL(10,2) CHECK (total_amount >= 0)
);

-- one query, two tables
SELECT u.email, o.order_id, o.total_amount
FROM users u JOIN orders o ON o.user_id = u.user_id
WHERE u.user_id = 12345;

Its superpower is the ACID transaction: a group of changes either all happen or none do. Move money from account A to B, and you’ll never see it leave A without arriving in B.

  • Use it for: orders, payments, accounts, inventory, anything where correctness matters more than raw speed.
  • The catch: scaling reads is easy with read replicas. Scaling writes across many machines means sharding, which is hard work. Big schema changes on large tables need care.

2. Key-value stores

The simplest model there is: a key points to a value. Think of a giant HashMap that lives on a server, shared by all your app instances.

// Java · Spring Boot + Redis: a session that deletes itself after 30 minutes
redis.opsForValue().set("session:" + sessionId, userId, Duration.ofMinutes(30));
String userId = redis.opsForValue().get("session:" + sessionId);

Redis keeps data in memory, so reads take well under a millisecond. Keys can expire on their own (a TTL), which is perfect for temporary data.

  • Use it for: sessions, caches, rate-limit counters, leaderboards, shopping carts.
  • The catch: you can only ask “give me the value for this key.” No “find all users in Pune.” And memory is expensive, so when Redis fills up, its eviction policy decides what happens: refuse new writes (noeviction), or drop the least recently used keys (allkeys-lru).

3. Document databases

Data is stored as JSON-like documents. A document can hold nested objects and lists, and two documents in the same collection don’t need the same fields.

{
  "_id": "prod_881",
  "name": "ThinkPad X1",
  "price": 1299,
  "specs": { "ram": "32GB", "screen": "14in" },
  "tags": ["laptop", "business"]
}

A shirt in the same collection can have "specs": { "size": "M", "colour": "blue" }. No migration needed.

The big design question is embed or reference:

  • Embed related data inside the document when there are only a few and you read them together (a user’s 2–3 addresses).

  • Reference by ID when there are many, or they change on their own (a user’s thousands of orders).

  • Use it for: product catalogs, user profiles, content management, data that is naturally nested.

  • The catch: joins are weak, so you often duplicate data to read it fast, and keeping copies in sync is your job. “Schema-less” really means the schema lives in your code, and messy data builds up if you’re careless.

4. Wide-column stores

A wide-column store like Cassandra spreads rows across many machines by a partition key, and keeps rows inside each partition sorted (often by time). Every node is equal, so you add machines and get more capacity, close to linearly.

-- Cassandra (CQL): all of one chat's messages live together, newest first
CREATE TABLE messages (
    chat_id    UUID,
    sent_at    TIMESTAMP,
    sender_id  UUID,
    body       TEXT,
    PRIMARY KEY (chat_id, sent_at)
) WITH CLUSTERING ORDER BY (sent_at DESC);

“Get the latest 50 messages for chat X” goes to one partition and reads a sorted slice. Very fast, even with billions of rows.

  • Use it for: message history, activity feeds, event logs, IoT data. Huge write volumes with a known read pattern.
  • The catch: you design tables around your queries, not around your entities. A query you didn’t plan for usually means a new table. No joins, and consistency is tunable (ONE, QUORUM, ALL) rather than strict by default.

Don’t mix this up with columnar databases

The name causes confusion. Columnar analytics databases (ClickHouse, BigQuery, Redshift) store each column together on disk. That’s a different thing, built for a different job:

Left: a row store keeps each row together on disk, so a query for one order reads one compact block, which is good for transactions. Right: a column store keeps each column together, so a query for the average of the amount column reads only that one column and skips name, email and city, which is good for analytics. A query 'SELECT AVG(amount) FROM orders' highlights just the amount column in the column store, versus every block in the row store.
Row stores are fast at 'give me this whole record'. Column stores are fast at 'add up this one field across a billion records'.

If you need to answer “total sales per country last year” over billions of rows, a columnar database does it in seconds. Your transactional database would struggle and slow down checkout while it tried.

5. Graph databases

Data is nodes (people, products, places) joined by edges (FRIENDS_WITH, BOUGHT, LIVES_IN). The edges are stored as direct links, so following them is cheap.

Left: a small graph. Alice is friends with Bob and Chen, who are friends with Dee, Eli and Fay. The friends-of-friends query hops along the edges from Alice to Bob and Chen, then on to Dee, Eli and Fay, written in Cypher as MATCH (me {name:'Alice'})-[:FRIENDS_WITH]->()-[:FRIENDS_WITH]->(fof) RETURN fof. Right: the same question in SQL joins the users table to the friendships table, then friendships to itself again. Each extra hop adds another join, and a cost bar grows with every join: fine for one or two hops, slow and hard to read at three or four hops on millions of rows.
In a graph database, each hop follows a stored link. In SQL, each hop is another join, and the cost grows with every hop.
// Neo4j (Cypher): "people who liked what I liked also liked..."
MATCH (me:Person {name: 'Alice'})-[:LIKES]->(m)<-[:LIKES]-(other)-[:LIKES]->(rec)
WHERE NOT (me)-[:LIKES]->(rec)
RETURN rec.title, count(*) AS score
ORDER BY score DESC LIMIT 10;
  • Use it for: social networks, recommendations, fraud rings (“these 20 accounts share one phone number and two cards”), knowledge graphs.
  • The catch: it’s overkill when your data isn’t really about connections. Graph databases are also harder to spread across many machines.

6. Time-series databases

Built for data that arrives in time order and is read by time range: CPU usage, sensor readings, stock prices. Each point is a timestamp, some tags (host=server1, region=ap-south) and values (cpu=45.2).

What makes them special:

  • Very fast appends. Data is almost never updated, only added.

  • Strong compression. Readings that change slowly compress very well.

  • Downsampling. Keep per-second data for 7 days, per-minute averages for a year.

  • Retention. Old data is deleted automatically.

  • Use it for: monitoring, IoT, financial ticks, anything you’d draw as a line chart over time.

  • The catch: they’re poor at general-purpose data. Don’t store your users here.

One more: object storage

Photos, videos, PDFs and backups don’t belong in any database. Put the file in an object store like Amazon S3, and keep only its metadata (owner, upload time, S3 key) in your database. It’s far cheaper, and it plugs straight into a CDN.

How to choose: start simple

Here’s the honest default for most systems:

“Start with PostgreSQL and Redis. Add another database only when a specific access pattern proves you need it.”

PostgreSQL for your source of truth, Redis for speed. Together they cover most products for a long time. Then let each access pattern pull in what it needs:

A decision flow. Start: what does this data need? If it needs transactions and joins, use relational (PostgreSQL). If it's looked up by key only and must be very fast or expire, use key-value (Redis). If its structure varies and it's read as one nested object, use document (MongoDB). If it's huge write volume read by one key in time order, use wide-column (Cassandra). If the questions are about connections several hops deep, use graph (Neo4j). If it's measurements over time, use time-series (InfluxDB or TimescaleDB). If it's aggregations over billions of rows, use a columnar store (ClickHouse). If it's files, use object storage (S3). Not sure? Default to PostgreSQL.
Ask what the data needs, not which database is popular. When in doubt, PostgreSQL.

Using different databases for different jobs in one system has a name: polyglot persistence.

An online shop with five services, each with its own store. Order service uses PostgreSQL for transactions. Cart service uses Redis for fast, expiring data. Catalog service uses MongoDB for flexible product data, with Elasticsearch for full-text search. Analytics uses ClickHouse for big aggregations. Media service uses S3 for images. A caption warns that every extra database adds backups, monitoring, upgrades and on-call knowledge.
Each service picks the store that fits its data. Each extra store is also one more thing to run, back up and understand.

It’s powerful, but every extra database has a cost: backups, monitoring, upgrades, security patches, and someone on call who understands it. Add one when the pain of not having it is real, not because it’s fashionable.

In interviews, the difference shows:

  • Weak: “I’ll use MongoDB because NoSQL scales.”
  • Strong: “PostgreSQL for orders because we need transactions. Redis for sessions because we need speed and expiry. Elasticsearch for product search because we need full-text search.”

What breaks, and how to fix it

What breaks What you see The fix
Connection pool runs out Slow queries hold every connection, new requests time out with 500s Right-size the pool, set connection and query timeouts, add a circuit breaker
The primary database dies Every write fails A standby replica with automatic failover, plus serving cached data where you can
One slow query A full-table scan spikes CPU and slows everyone Find it with pg_stat_statements, add an index, paginate, move reports to a replica
Bad data from a bug Negative balances, orphan records Let the database guard you: NOT NULL, CHECK, foreign keys, unique constraints
Data corrupted or deleted Wrong data everywhere Point-in-time recovery, and test your restores. A backup you’ve never restored is a hope, not a backup

Puzzle 1: storing a billion photos

500 million × 2 MB is about 1 PB of new photos a day. That never goes in a database.

  • Photos → object storage (S3), served through a CDN so popular photos are cached close to users.
  • Photo metadata and users → PostgreSQL: owner, upload time, S3 key, follows.
  • Comments and likes → a wide-column store like Cassandra: huge write volume, read newest-first per photo.

The app reads the metadata, builds the CDN URL, and the CDN serves the bytes. Keep files and facts about files apart.

Puzzle 2: the last item in stock

Both read stock = 1, both pass the check, both write stock = 0, and two orders are created for one item. @Transactional alone doesn’t stop it.

Three fixes, from simplest:

  1. Let the database do the check atomically: UPDATE items SET stock = stock - 1 WHERE id = ? AND stock > 0. If it updated 0 rows, it’s sold out.
  2. Optimistic locking: add a @Version field. The second save fails because the version changed, so you retry or report “sold out”. Best when clashes are rare.
  3. Pessimistic locking: SELECT ... FOR UPDATE locks the row until the transaction ends. Safe, but buyers queue up behind the lock on hot items.

Puzzle 3: adding a column to 100 million rows

The danger is a change that rewrites or locks the whole table, or code and schema getting out of step. Do it in small, backward-compatible steps:

  1. Add the column as nullable. In PostgreSQL this is a quick metadata change, with no table rewrite.
  2. Deploy code that copes with NULL.
  3. Backfill in small batches (say, 10,000 rows at a time) during quiet hours.
  4. Only then add NOT NULL, once every row has a value.

Test it first on a copy with production-sized data, and have a rollback plan.

Key takeaways

  1. There is no best database. Each type is fast at the access pattern it was built for.
  2. Relational for transactions and integrity. Key-value for speed and expiry. Document for flexible, nested data.
  3. Wide-column for huge write volumes with known queries. Graph for multi-hop relationships. Time-series for measurements over time.
  4. Wide-column is not columnar. Columnar stores like ClickHouse are for analytics over billions of rows.
  5. Files go in object storage, with only their metadata in a database.
  6. Start with PostgreSQL and Redis. Add more only when a real access pattern demands it, because every new database is one more thing to run.

This opens the Data storage & data modeling thread. Picking the right database is half the job. A good schema in a “wrong” database often beats a bad schema in the right one, so next we’ll look at data modeling: how to shape your data for the questions you’ll ask it.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.