How different databases store and find your data
What I’m learning from DDIA chapters 2, 3 and 4, with diagrams and a couple of specialized systems.
I’ve been planning to write about the different database types and how they work, with diagrams to help explain what’s happening underneath.
I’m currently reading Designing Data-Intensive Applications, and this post comes from the notes I’ve been putting together from chapters 2, 3 and 4. I’ve also included time-series and vector databases because I wanted to look at where those fit.
Basically, I want to follow the data. Where does a new record go? When we ask for it later, how does the database find it? And if we change it, what happens to the old value and the indexes pointing to it?
Let’s work through those questions using the diagrams. The examples are small enough to follow by hand, but we’ll also get into what becomes expensive as the data grows.
The categories overlap
First, some of the names we’ll be using refer to different things.
Relational, document, graph and key-value describe how we organize or access data. OLTP and OLAP describe the kind of work we’re asking the system to do. Row storage and column storage describe how values are laid out. B+trees, LSM-trees and inverted indexes get into the structures that help with storing and finding those values.
So one database can be relational, store records by row, handle transactions and support full-text search. Another can expose SQL tables while using columns for analytical reads. We aren’t choosing one label from the whole list and excluding the rest.
Now take a file containing a million user records. Storing those records gives us somewhere to keep the data. Finding user 42 is another job. Unless we have a useful way to locate that record, we may have to examine a lot of the file.
That’s where an index comes in. It keeps information the engine can use to narrow the search: ordered keys and row locations, hash entries, lists of documents containing a word, or links between nearby vectors. We’ll see why those arrangements suit different queries.
There’s more around them in a running database, including caching, transactions, crash recovery and replication. The diagrams leave most of that out so we can follow the particular read or write being explained.
Relational databases
Let’s start with Postgres and MySQL. You store records in tables, with columns for their fields. Keys identify each record and let one table refer to another.
Take for instance my user record in the diagram. It has company_id = 7. The company table tells us that company 7 is Acme. A JOIN matches users.company_id with companies.id, so we can ask for the user and the company’s details in one query.
Why keep those details separately? Imagine Acme changes its name. We update the company record, and users still refer to company 7. If we’d copied the name into every employee’s record, we’d have to find and update those copies too. Keeping shared facts in one place is part of what normalization gives us.
Reading user 42
For a profile page, one possible execution plan starts with an index on users.id. The database finds 42, fetches that row, reads its company_id, then uses an index on companies.id to find Acme. It returns the columns we asked for from both records.
That sounds straightforward because we’re fetching one user. Ask for thousands of users and their companies, and the same approach means thousands of lookups. The engine has other options. A hash join can build a lookup structure from one input and probe it with the other. A merge join can walk two inputs ordered by the join key, matching values as it goes.
The optimizer estimates the work involved and chooses a plan. An index existing on a table doesn’t guarantee that it will use it. If we need most of the rows, reading the table’s pages in a scan can be cheaper than following lots of index entries to scattered row locations. PostgreSQL’s EXPLAIN guide lets us inspect that choice.
Writes have their own work. Inserting a user may require checking a unique ID and a foreign key, updating indexes, and recording information needed for recovery. Adding indexes helps certain reads, but every applicable index also needs maintaining when the indexed data changes.
A transaction can group related changes so they commit together. For example, creating a company and its first employee shouldn’t leave the employee pointing to a company that wasn’t saved. The tables describe that relationship; constraints and transactions help enforce it, while the query plan determines how much work retrieving it takes.
Document databases
With document databases like MongoDB and Couchbase, a record can contain nested objects and arrays. A user profile might hold the user’s name, addresses and preferences together.
Fetching user 42 can return that whole profile from one document. The application doesn’t have to fetch each address separately before it can show the profile page. We’ve shaped the record around information that this screen needs together.
But then you have to decide what to embed and what to reference. Addresses belonging to the user fit naturally inside the profile. A company’s current name and official address are shared by many users. Embed those details in 10,000 profiles, and a company address change leaves us with 10,000 copies to update. Store a company ID instead, and reading its details requires another lookup or join.
There are cases where a copy is useful. An invoice may need to preserve the address used when it was issued, even after the company moves. That copy represents a historical fact. A profile displaying the company’s current address has a different requirement.
Finding something inside the document
Now change the question from “fetch user 42” to “find every user with an address in Lagos.” The nested shape alone doesn’t give the database a quick route to those users. It needs to search the relevant field, using an index if an appropriate one exists.
MongoDB supports multikey indexes for array fields. An array can contribute multiple indexed values, allowing the index to identify documents with a matching array value. That also means one document may require several index entries. Changing its addresses can involve maintaining those entries as well as updating the stored document.
So putting addresses inside a profile helps us read the profile together. Finding profiles by an address is a separate access pattern that still needs planning.
The document boundary matters for writes too. If a user changes a preference and an address together, MongoDB’s single-document atomicity lets a write affecting those fields take effect atomically. Related changes spread across documents may need a transaction or another consistency strategy.
That boundary needs a sensible size. A few addresses fit comfortably in a profile; every event the user has ever generated creates an array that keeps growing. Flexible documents let us choose the shape, but we still have to account for how much data accumulates, which values change together, and which facts are shared elsewhere.
Graph databases
Graph databases like Neo4j make entities and their connections explicit. People, companies and places become nodes. Relationships connect them, and both nodes and relationships can carry properties.
In the diagram, Udoka works at Acme, and Acme is located in Lagos. To answer “who works for companies in Lagos?”, we can find the Lagos node, follow incoming LOCATED_IN relationships to companies, then follow incoming WORKS_AT relationships to people.
The query describes a pattern through the connections. If we’re asking where one particular person works, starting with that person and following the relationships outward may make more sense. The starting point and direction affect how much of the graph we need to visit.
An index on a property, such as a city’s name, can help locate the Lagos node. From there, the query follows the relevant stored relationships. Finding Lagos and finding everyone connected to it are different pieces of work: making the first lookup quick doesn’t remove the cost of the second.
What happens as the graph grows?
Imagine Lagos connects to thousands of companies, each with hundreds of employees. Returning all those people means visiting a large neighborhood. If the question only concerns one department, checking that condition at an appropriate point can reduce the records carried through the query.
Longer paths add another complication. “Who is connected to this person within three relationships?” can branch into many possibilities at every step. Different paths may overlap or revisit nodes. We have to specify which relationship types count, which directions to follow, whether repeated nodes are allowed, and where the search stops.
This is useful work when connections are central to the question. A dependency investigation can follow service A to its dependencies, then follow those services to theirs. A recommendation can go from people to items and back to other people. Fraud investigations may need to explore several connected accounts or entities. The result we’re looking for can be a path or a neighborhood.
Relational tables can represent these connections too. The graph model gives us a direct way to express and explore them, with traversal costs that depend on the paths we ask it to follow.
Those relationships also need maintaining. Moving Udoka to another company changes the relevant WORKS_AT relationship; moving Acme changes its LOCATED_IN relationship. Constraints and transaction rules still matter, especially when several connection changes need to happen together.
Key-value databases
Key-value databases are basically: here’s a key, give me its value. A request carrying a session ID is a familiar example. We know which session we want and need to fetch its state.
Redis and DynamoDB support this model, although their capabilities and internals are very different. Caches and other records fetched by identifier also fit this access pattern.

The diagram shows Bitcask, one particular storage design. A write appends a record to a file. A hash index in RAM tracks where the newest value for each key lives in that file.
Suppose we write user:42, then update it later. The update appends another record and changes the index to point at the new location. Now GET user:42 consults the index and reads that record. It doesn’t have to scan the log to work out which version is current.
What the hash index gives us
A hash function turns a key into a value used to locate a bucket or slot. Different keys can produce the same hash, so the structure needs collision handling and must distinguish the actual keys. PostgreSQL’s hash-index documentation describes one implementation using buckets and overflow handling.
The useful part for our example is approaching the exact key directly. But hashing doesn’t keep keys sorted. Asking for users 40 through 70 in order needs a different access path. So does “find every user in Lagos”: the hash index on user:42 can’t discover a city stored inside its value.
In Bitcask, the disk record holds the value and the in-memory directory tells us where to find its current version. Keeping that directory in RAM makes its size a constraint as the number of keys grows.
Earlier versions remain on disk after an update. A merge process reclaims obsolete records; without it, repeated updates would keep adding old values to the files. Appending simplifies the immediate write path, while cleanup creates work that happens later.
For sessions, knowing the key is usually enough. If the application starts asking to search sessions by arbitrary properties, we’ll need additional indexes or another way to organize those queries.
The key-value API also tells us little about recovery. Losing a cache that can be rebuilt from another database has different consequences from losing the only copy of an order. We still need to understand the chosen system’s persistence and recovery behavior.
OLTP and B+trees
OLTP means online transaction processing. Creating an order, fetching an account and booking a seat are examples. A typical operation works on a relatively small number of records, even though the database may contain millions. Postgres and MySQL commonly handle this kind of workload.
For the lookup in this diagram, we’re using a B+tree index.
The tree is organized into pages, which are blocks of stored data. An internal page holds separator keys and pointers to pages below it. The leaf pages hold the entries we’re searching for. In this example, those entries point to table rows; other storage arrangements can keep row data in the leaves.
Take user 42. At the top, the separators tell us to follow the branch for keys at least 40 and less than 70. We reach the appropriate leaf, find 42, then follow its pointer to the table row. We haven’t checked every user to get there.
A page can hold many separators, so one step can choose among many branches. That helps keep the tree shallow. It’s a different shape from a binary tree, where each node gives us only two directions.
The leaves are ordered and linked too. For IDs 42 through 65, we can locate 42 and continue through the entries until we pass 65. We don’t have to go back to the root for every ID in the range. Returning a large range still takes work, though. Finding the first row quickly doesn’t remove the cost of fetching the rest.
Writes have to keep this arrangement valid. Inserting a key means finding its place in the tree. If the page can’t fit another entry, it may split, and the parent gets a pointer to the new page. The parent can run out of room as well, so a split can move upward. PostgreSQL’s B-tree documentation goes into those page structures.
Which values are we ordering?
Now suppose we’re fetching a user’s latest orders. An index on (user_id, created_at) keeps one user’s orders together, ordered by creation time. Once we find that user’s part of the index, the dates we’re interested in are within it.
Swap the columns to (created_at, user_id) and the arrangement changes. The dates come first, with different users’ orders grouped within those dates. The index contains the same fields, but it offers a different route through them. This is why the order of a composite index matters. PostgreSQL’s multicolumn-index guide explains which conditions narrow the scanned portion, including cases where skip scans help.
There’s also a difference between finding a row and having all the values we need. If the index gets us an order’s location but the query asks for its total and shipping address, we still need those values from the table.
A covering index stores additional values needed by a query. It can make an index-only scan possible, subject to the engine’s rules. PostgreSQL also checks row visibility, as described in its covering-index documentation. Adding those values uses more space and gives writes more to maintain, so the benefit depends on the query.
The tree handles locating and ordering data. Making a group of changes commit together or roll back needs transaction machinery as well. An OLTP workload doesn’t require one particular index or storage engine.
Wide-column databases and LSM-trees
With wide-column databases like Cassandra and ScyllaDB, related rows are grouped by a partition key. Clustering keys then order rows inside that partition.
Take events from host A. We want to fetch that host’s events for a particular time range, so the table can group them by host and put them in timestamp order.
It may also help to include a time bucket in the partition key. With (host_id, day) as the partition key and timestamp as the clustering key, a query supplies the host and day, then reads the required times. A window crossing midnight may need two day partitions.
The day gives us a boundary. Otherwise, a busy host’s partition could keep growing as events arrive. The bucket size depends on how many events we’re storing and how much time a typical query covers.
But ask “which hosts had errors in the last hour?” and we no longer have a particular host to start from. We may need another table arranged for that query. Then an incoming event has to be written to each required representation, and those copies need to stay consistent. That’s the practical part of query-driven modeling.

Underneath that model, these systems use an LSM engine. LSM stands for log-structured merge. A write goes through a recovery log and into a memtable, which buffers updates in memory. Flushing that buffer creates an immutable sorted file called an SSTable.
Sorting helps with both finding keys and merging files later. Think of a file containing a, b, c, d in order. An index can identify the block where a key belongs, then the reader searches that block. We don’t necessarily need an in-memory entry for every key just to narrow the file search. File formats differ; RocksDB’s block-based SSTable format is one example.
Reading a key that has changed
Now say key a was written with value 1, the memtable was flushed, and a later write changes it to 3. We haven’t edited the old SSTable in place. The new version lives in a newer layer until it, too, is flushed.
So a read has to consider the relevant in-memory and on-disk data and reconcile the versions it finds. The first file containing a isn’t enough to establish the answer. It might contain the older value. Cassandra’s storage-engine guide follows this process.
Checking many files would add read work. A Bloom filter helps reject files that can’t contain the requested key. It answers “definitely absent” or “possibly present.” If it’s possibly present, we still check. A false positive sends us to a file unnecessarily; it doesn’t make a missing record appear in the result.
Cassandra uses these filters for partitions in SSTables. Giving a filter more memory can reduce false positives and unnecessary I/O. Its Bloom-filter documentation explains that trade-off.
Compaction brings the files together. It reads sorted runs, resolves versions and writes new files. In the diagram, the newer a:3 supersedes a:1. This means one application write can result in several physical writes over time, which is what write amplification refers to.
Deletes need handling too. If we remove a only from the newest layer, an older copy could become visible again. A tombstone records the deletion so reads and compaction can account for it. When that marker can safely be removed depends on the engine’s recovery and replication rules.
Buffering makes the initial write path useful for this workload, but the database still has files to read, merge and clean up. It also needs disk space while that work is happening. And the wide-column model we’ve been discussing is separate from the analytical column layout coming next.
OLAP and column storage
So far, most of our examples have involved fetching or changing a few records. “What’s our revenue by country?” is a different kind of question. We might need to add up amounts across millions of orders, but never look at the customer names or shipping addresses.
That’s the sort of work OLAP, online analytical processing, describes. ClickHouse and BigQuery are examples of systems built for analytical workloads. To understand why column storage helps here, let’s use the small table in the diagram.
In a row layout, each order’s fields sit together: its ID, name, country and amount. That makes sense when we’re opening one order and need all its details. But for SUM(amount) WHERE country = 'NG', pages containing names and IDs bring along data the query won’t use.
A column layout puts country values together and amount values together. The query can find the matching positions in country, then add the corresponding amounts: 10, 30 and 40, giving us 80. As records get wider, avoiding entire unused columns saves more reading.
Repeated country codes are also easier to compress together than a sequence alternating between names, numbers and addresses. Processing batches of the same type reduces per-value overhead too. ClickHouse explains these connections between column layout and analytical reads.
Can we skip some rows as well?
Reading only two columns doesn’t automatically mean reading only the matching rows. If Nigerian orders are scattered throughout the data, the engine may still inspect country values across a large part of the table.
Now suppose the data is sorted by country. Matching values occupy a narrower region, so the engine has a chance to rule out other regions before reading their contents. The sort order is doing useful work here.
ClickHouse’s MergeTree family uses a sparse primary index. Rather than keeping an index entry for every row, it records key values at the boundaries of granules, groups of rows. The engine uses those entries to identify granules that might contain matches, then reads and checks the relevant values inside them.
That makes the sort key a consequential choice. Sorting by country helps our country filter; sorting primarily by an unrelated field may leave matching orders spread across many granules. The word “index” alone doesn’t tell us how much of this report we’ll avoid scanning.
Getting new orders into the report
In MergeTree, inserts create sorted data parts, and background merges combine parts. Loading a batch gives sorting and compression more data to work with; lots of tiny inserts can create many parts to maintain. Updating older values also requires engine-specific maintenance.
There’s another timing question if orders are copied from a transactional database. An order can be committed there before it reaches the analytical copy. A revenue total needs a clear freshness expectation, especially if someone uses it to reconcile payments. Fast aggregation and up-to-date ingestion are separate pieces of that result.
Search engines and inverted indexes
Suppose we’ve stored a collection of articles and someone searches for “fast database.” Checking every article’s text each time would repeat a lot of work. Search engines such as Elasticsearch and OpenSearch prepare a structure that lets the query start with the words instead.
That structure is an inverted index. It maps an indexed term to the documents containing it. The list of documents for a term is called a posting list.
In our diagram, the list for “fast” contains D1 and D3. The list for “database” contains D1 and D2. A query requiring both terms intersects those lists, leaving D1. If either term is enough, their union gives us D1, D2 and D3.
We’ve moved work to the write side: build and maintain the lists ahead of time, so reads can find candidates without scanning every article. The index takes storage, and changing an article means updating its searchable representation.
What did the index actually store?
Before those lists exist, an analyzer turns text into searchable terms. It might lowercase words, split them into tokens or apply language-specific transformations. Query text needs compatible analysis. If the article’s “Database” becomes “database” when indexed, searching with a different treatment can produce surprising matches or misses.
This is why choosing an analyzer changes the search experience. Stemming can bring word forms together; removing stop words can affect phrase matching. Some changes require rebuilding the index because the existing terms were produced under the old rules. Elastic’s full-text search guide walks through that pipeline.
Posting lists can also store term frequencies and positions. Take the phrase “fast database.” A document containing both words doesn’t necessarily contain that phrase. The words might be far apart, or “database” might come first. Positions let the engine check their order and proximity.
Frequencies contribute to ranking, alongside signals such as how common a term is across the collection and document length. Finding matching documents gets us a candidate set; scoring determines their order. A common word may produce thousands of candidates, while a rarer word narrows the set much more.
Saving an edit and finding it in search
Say we edit D1 and remove “fast.” Elasticsearch analyzes the replacement text and updates the index. But accepting that write doesn’t mean every search can see it immediately. A refresh makes recent changes searchable, which explains the near-real-time behavior.
Underneath, searchable segments accumulate. Updates replace a document’s representation and leave obsolete entries to be reclaimed through segment merging. So writes involve analysis now and maintenance later.
If the original article lives in another database, the application also needs to deliver edits and deletions to search. A failed or delayed update can leave an old title in the results. Retries and rebuilding the index matter just as much as the posting lists when someone expects search to reflect the article they just saved.
Time-series databases
Beyond those DDIA chapters, I wanted to look at a couple of specialized types too. Time-series databases such as InfluxDB and TimescaleDB deal with timestamped measurements and events: CPU readings, sensor values, request counts and similar growing histories.
Take CPU measurements for host A. We’re usually asking for a bounded period, perhaps its average CPU from 10:00 up to, but excluding, 11:00. We don’t want the database to search a year’s worth of readings to answer that.
First find the period, then the measurements
Time partitioning groups records by period. With our query, the engine can reject chunks whose time ranges don’t overlap 10:00–11:00. That’s a useful first cut, but the remaining chunk can contain readings from hundreds of hosts.
So there’s another step inside it. An index on host and time can help locate host A’s readings in the requested interval. Partitioning narrows which chunks we consider; the index narrows the records within them. TimescaleDB’s hypertable documentation describes how chunks and their indexes work together.
The storage arrangement depends on the system. InfluxDB’s partitioning documentation, for example, describes organizing data with time and tags. Those choices need to follow the queries: all hosts during an incident and one host’s monthly history aren’t asking for the same access pattern.
Writes continually add measurements, often in batches. Time ordering can give similar values opportunities to compress together. But readings don’t always arrive in order. A delayed measurement may belong to an older chunk, and it may change a summary we already calculated.
The number of distinct series matters as well. Host, device and sensor tags identify combinations of measurements. Adding a changing request identifier as a tag can create a huge number of combinations. The cost depends on how the engine represents and indexes those series.
What do we lose when we keep summaries?
Suppose we record CPU once a second but display an hourly dashboard. Keeping count, sum, minimum and maximum for each hour lets that dashboard read much less data. Compression helps store the raw readings; rollups reduce how much the query needs to process.
But an hourly summary can’t reconstruct a ten-second spike. And combining summaries needs care. One period with two readings averaging 90 and another with eight averaging 10 gives an overall sample average of 26, not 50. We get 26 by combining their sums and dividing by the combined count.
That’s a sample-weighted average. If readings arrive at irregular intervals and we want average CPU over time, we need to account for duration too. Missing measurements aren’t automatically zeroes.
A retention policy might keep raw readings for a month and summaries for a year. That saves storage, but after the raw readings expire, some questions become impossible to answer. Late data, summary recalculation and retention therefore belong in the design alongside the database and its indexes.
Vector databases
Now suppose someone asks a question about our articles without using the exact words they contain. We can represent articles and questions as embeddings, numeric vectors produced by a model, then look for nearby vectors. Pinecone and Milvus are examples of databases supporting this kind of retrieval.
What counts as nearby depends on the embedding model and distance metric. The database searches the representation we’ve given it; a close vector isn’t automatically a useful answer.

How the graph cuts down the search
Let’s start with the straightforward approach. To find the ten nearest articles, calculate the question vector’s distance to every article vector and keep the closest ten. That exact search gives us a reference result, but its comparisons grow with both the number of vectors and their dimensions.
HNSW, Hierarchical Navigable Small World, builds a graph to explore fewer candidates. Each vector is connected to selected neighboring vectors. Some appear in upper layers, producing a sparse graph above the denser bottom layer.
Search begins at an entry point high up. It compares connected vectors and moves toward closer ones, using the sparse layers to cross the space. It then descends, using the position found above as a starting point below. At the bottom, it explores a larger set of promising candidates before choosing results.
That can avoid comparing the query with the whole collection. But the links don’t guarantee a route through every true nearest neighbor. A search can miss one, which is why this is approximate nearest-neighbor search. The HNSW paper describes the layered structure behind our simplified diagram.
What changes when we build or query it?
Inserting a vector involves searching for suitable neighbors and adding links. Milvus exposes M to control graph connections and efConstruction to control the candidate search during construction. More links use more memory; greater construction effort takes more build time and can produce a better graph.
At query time, ef controls the search candidate list. Increasing it usually gives the search more opportunities to find good neighbors, at the cost of more comparisons and latency. This changes query effort without rebuilding the graph.
We can measure that trade-off against exact search. If the exact top ten contains ten neighbors and approximate search returns eight of them, recall@10 is 0.8. That’s agreement with the exact vector result. Whether those articles actually help answer the question needs its own evaluation.
Filters complicate the search. Perhaps we only want articles in one collection, or records the reader has permission to access. Filtering after retrieving a small candidate set can leave too few results. Applying constraints during retrieval changes which candidates are available, and implementations handle this differently. The filtered query needs to be measured directly.
Chunking and the embedding model matter before any of this. Changing models can require embedding the corpus again and rebuilding the index. HNSW’s graph organizes vectors for similarity search; unlike the earlier graph database, its links don’t express relationships such as WORKS_AT between people and companies.
When the application changes
Chapter 4 brings in something that affects all these database choices: encoding and schema evolution. A stored record can outlive the application version that wrote it. During a deployment, old and new code can also run at the same time.
Take a user record with an ID and name. Version 2 adds email. Some records still come from version 1, and some requests still reach version 1 processes. We need to work through what happens in both directions.
Can both versions read the record?
The diagram uses binary Protocol Buffers. Encoded fields carry numeric tags that identify them, together with wire-type information that tells the parser how to read or skip their values. The field name in our source code isn’t what identifies the field in those bytes.
When a new reader reads an old record, email is absent. Its handling of presence or a default value lets it decode the record. That’s backward compatibility: newer code can read older data. But then the application needs to decide what “no email” means. A parser successfully decoding the message doesn’t make an email-dependent feature work.
In the other direction, an old reader can skip the unfamiliar email field in a newer message. That’s forward compatibility. The Protobuf guide explains the rules for compatible changes.
Field numbers need to remain stable. If we delete a field, reserving its number prevents a later field from accidentally reusing it. Otherwise, old bytes can acquire a new interpretation. Changing an existing field’s type needs separate consideration; the compatibility of adding a field doesn’t apply to every possible edit.
These examples concern the binary format. Converting messages through JSON or copying selected fields into a new message can change what survives. We need to check the actual path a record takes, including old services that read and write it again.
Decoding correctly isn’t enough
Suppose amount stays an integer, but version 1 interprets it as naira and version 2 interprets it as kobo. Both versions can decode the same number. They disagree by a factor of 100 about the amount of money it represents.
A separate field with explicit units, or a versioned representation, gives the change a distinguishable meaning. Then we can plan the rollout: teach readers to understand the new representation, move writers to it, backfill old records where needed, and eventually retire the old one.
The overlap matters. If old code still needs the original field, removing it too early breaks that code. If we roll back after writing new records, the older application must still handle what was stored during the rollout. A new status value can cause the same problem even when its encoded type hasn’t changed.
So a migration includes readers, writers and existing data, with a period where more than one version may coexist. A document database might accept an extra JSON field immediately, but the programs reading it still need a shared interpretation. Storage flexibility doesn’t settle that part for us.
What I’d start with
After going through all of this, I’d start with a few actual queries.
Take an order application. Creating an order and fetching its current state are small transactional operations. A revenue report reads across many orders. Searching descriptions needs a way to match and rank text. Finding descriptions similar to a question brings embeddings into the picture.
They’re all using order data, but they’re asking the database to do different work. That doesn’t mean the application immediately needs four databases. The existing system may already handle several of those requirements.
For a slow query, the filters, sort order and result size give us somewhere to begin. Then we can inspect the query plan or the engine’s equivalent. Is it scanning too many rows? Fetching table values after finding index entries? Checking several sorted files? Does the result itself contain so much data that returning it is expensive?
That last one is easy to overlook. An index can help locate matching records, but if we’re asking for a million of them, there’s still a million-record result to deal with.
A report also has a freshness requirement. We may be able to make it cheaper by reading a copied dataset or a precomputed summary, but then we have to decide how that copy is updated and how far behind it can be. Adding search or vector retrieval raises similar questions about keeping another representation of the data current.
So that’s where I want to take these DDIA notes: from the query to the structure serving it, then to the work of maintaining that structure. Before adding another system, I want to understand which part of the problem it would solve and what else we’d have to run alongside it.








