Choosing a Database · Lesson 70 of 112

Database How to Choose

What you will learn

  • The questions to ask before choosing
  • Why a relational database is the safe default
  • When another kind is worth it
  • Why using more than one is normal

1. Ask these questions

Question Points toward
Must the data be exact and linked (money, orders, accounts)? relational
Does every record have a different shape, mostly read whole? document
Do you only fetch by a known key, very fast, maybe temporarily? key-value or cache
Are the connections themselves the question (friends, routes)? graph
Huge, steady, time-ordered writes read by key and range? wide-column
Big reports over lots of history? analytical (column-oriented)

Then check the practical side:

  • Questions you will ask later. SQL answers questions nobody planned; a layout built around known questions may not.
  • Rules. Who keeps the data correct, the database or every program?
  • Size and growth. Most projects are far smaller than they fear.
  • Who will run it. Backups, updates and security (chapter 8) are work; a managed service can take some of it.
  • Skills. A tool your team knows well is worth a lot.
  • Cost and lock-in. How hard would it be to leave?

2. The checklist as code

This helper is a toy, not a rule. It only shows the order of thinking: exactness first, relational unless there is a clear reason:

def suggest(needs):
    if needs.get("money_or_orders"):
        return "relational"
    if needs.get("shape_varies"):
        return "document"
    if needs.get("fast_lookup_by_key") and not needs.get("complex_queries"):
        return "key-value"
    if needs.get("relationships_are_the_point"):
        return "graph"
    return "relational"

print(suggest({"money_or_orders": True}))
print(suggest({"shape_varies": True}))
print(suggest({"fast_lookup_by_key": True}))
print(suggest({}))
relational
document
key-value
relational

With no special need, the answer is relational. That matches common practice: it handles most data and most questions, and you can add a cache or another store later when a measured problem appears.

3. Other kinds you will meet

Four more names appear in real projects. Treat these as an orientation, not a full lesson on each.

Search engines. To find "tea with milk" in millions of texts, a search engine builds an inverted index: for every word, the list of documents that contain it. Searching then means looking up words, not reading every text. A tiny version:

docs = {1: "red tea with milk", 2: "green tea", 3: "milk and rice", 4: "rice"}
index = {}
for doc_id, text in docs.items():
    for word in text.split():
        index.setdefault(word, set()).add(doc_id)
print(sorted(index["tea"]), sorted(index["milk"]))
print(sorted(index["tea"] & index["milk"]))
[1, 2] [1, 3]
[1]

Documents with tea are 1 and 2, with milk 1 and 3, and with both only 1. Real search engines add ranking, spelling tolerance and language handling. Many relational databases also have a built-in full-text search for smaller needs (lesson 11.5).

Time-series databases. For data that is mostly "a value at a time" (temperatures, server load), they are built around time: fast appends, queries by time range, and summarising old data into coarser buckets. The bucketing idea in SQL:

import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE readings (sensor TEXT, ts TEXT, temp REAL)")
con.executemany("INSERT INTO readings VALUES (?,?,?)", [("s1","2026-01-01 09:10",20.0),("s1","2026-01-01 09:40",22.0),("s1","2026-01-01 10:05",21.0),("s1","2026-01-01 10:50",23.0)])
print(con.execute("SELECT sensor, substr(ts,1,13) AS hour, AVG(temp), COUNT(*) FROM readings GROUP BY sensor, hour ORDER BY hour").fetchall())
[('s1', '2026-01-01 09', 21.0, 2), ('s1', '2026-01-01 10', 22.0, 2)]

Four readings became two hourly averages. A small amount of such data fits an ordinary table.

Vector databases. Many AI tools turn text or images into lists of numbers called embeddings, where similar things get similar numbers. A vector database finds the stored items nearest to a query. The core calculation is a similarity score such as cosine similarity (1 means pointing the same way):

import math
def cosine(a, b):
    dot = sum(x*y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x*x for x in a)) * math.sqrt(sum(y*y for y in b)))
items = {"tea": [0.9, 0.1, 0.0], "coffee": [0.6, 0.3, 0.3], "rice": [0.0, 0.1, 0.9]}
query = [0.85, 0.15, 0.05]
for name, vec in sorted(items.items(), key=lambda kv: -cosine(query, kv[1])):
    print(name, round(cosine(query, vec), 3))
tea 0.996
coffee 0.897
rice 0.077

The numbers here are invented; real embeddings come from a model and have hundreds or thousands of values. A database for this must find near neighbours quickly among millions of vectors.

NewSQL. A label for systems that try to keep SQL and strict transactions while spreading data over many machines. Whether a given product fully achieves this is something to check in its own documentation; chapter 14 explains why it is hard.

4. Using several

Many systems use more than one database, each for what it does best. This is called polyglot persistence: relational for orders and accounts, a key-value store for sessions and caching, a search or analytical system for reports. Each extra system adds work: another thing to run, back up, secure and keep in step with the main data. Add one when a measured problem or a clear need appears, not before.

Worked example: a small online shop

Data Choice Why
Customers, orders, payments relational exact, linked, must be correct
Login sessions key-value (later, if needed) lookup by key, expire after a time
Monthly sales reports relational at first small data; add an analytical copy only if reports get slow

Start with one relational database. The shop is made up.

At a glance: the kinds side by side

Kind How the data looks Typical question Typical use Main trade-off
Relational (lesson 9.1) tables of rows, linked by keys "total per customer this month" orders, payments, accounts, students the shape is fixed in advance; spreading over many machines is harder
Document (9.2) one nested document per record "show this whole record" records whose fields differ, content, settings joins and cross-record rules are weaker
Key-value / cache (9.3) a value found by its key "what is stored under this key?" sessions, counters, cached answers only lookup by key; data may be temporary
Wide-column (9.4) rows grouped by key, with many columns "latest readings for this sensor" huge, steady streams of time-ordered writes you design the tables around the queries
Graph (9.4) points (nodes) and links (edges) "friends of friends" networks, routes, recommendations less suited to totals and plain tables
Analytical / column store (9.5, ch. 13) values stored column by column "average over three years" reports and dashboards slow for single-record changes

No kind is better in general. Start with a relational database unless you have a clear reason not to (lesson 9.1), and add another kind when a real need appears.

Common mistakes

  • Choosing by fashion, or because a large company uses it.
  • Choosing for a size you may never reach.
  • Ignoring who will back up and secure it.
  • Picking a database without writing down the questions you must answer.

Key takeaways

  • Start from the data, the questions and the rules, not from a product.
  • A relational database is the sensible default for most data.
  • Choose another kind when a clear need appears, and expect to combine several in bigger systems.
  • Every extra system costs running, backup and security work.

Practice

1. Which kind is the default when you are unsure, and why?

Show answer

Relational: it keeps data exact and handles most data and questions.

2. What does "the connections themselves are the question" point to?

Show answer

A graph database.

3. Why write down your questions before choosing?

Show answer

Different databases answer different questions well, so the questions decide what fits.

4. Why is using several databases not free?

Show answer

Each one must be run, backed up, secured and kept in step with the others.

5. A startup has 2,000 customers, orders and payments, and plans MongoDB, Redis and a graph database from day one to "scale to millions". Give advice.

Show answer

Start with one relational database: orders and payments must be exact, 2,000 customers is small, and each extra system adds running, backup and security work. Add a cache or another kind later when a measured problem or clear need appears.

6. Name the kind that fits best: (a) find all product descriptions containing certain words; (b) average temperature per hour for a year; (c) which stored items are most similar to this one; (d) friends of friends of Rina.

Show answer

(a) A search engine (or built-in full-text search); (b) a time-series database (or a table with time buckets if the data is small); (c) a vector database; (d) a graph database.