Databases

Where an app's data lives safely between requests.

What is it?

A running program keeps its variables in memory, but memory is wiped when the program stops or restarts. That's no good for a user's account, posts or orders.

A database is software built to store data reliably on disk, find it quickly, and keep it consistent while many things read and write at once. Almost every real app has one behind its server.

Explain like I'm 10

If the server is the chef, the database is the pantry and fridge: an organized place where ingredients (data) are kept, still there when the kitchen reopens the next day.

Examples

A server reading from a database

// Simplified example
async function getUser(id) {
  const user = await database.query(
    "SELECT * FROM users WHERE id = ?",
    [id]
  );
  return user;
}

The server doesn't store user data itself. It asks the database, which stores and returns it reliably.

How it works

A database organizes data (often into tables, or collections of documents) and gives you a query language or API to read and write it.

It also handles the hard parts for you: two simultaneous writes don't corrupt each other, and data survives a crash or restart.

Why does it exist?

Apps need data that survives crashes, restarts and many users at once. Building that from scratch for every app would be a huge waste, so every app relies on the same well-tested foundation instead.

When to use it

Use a database whenever data must outlive a single request or process: user accounts, orders, posts, anything that must still be there tomorrow or on another server.

When not to use it

For data needed only during one request (a temporary calculation, a value passed between two functions), a database is unnecessary overhead. Keep it in memory.

Common mistakes

  • Keeping important data only in server memory, so it's lost on every restart.

  • Not planning how the database will scale once data grows into millions of records.

  • Putting user input directly into a query, which opens security holes like SQL injection.

Practice exercises

  1. Easy:

    Explain why a to-do list app needs a database instead of keeping tasks in the browser's memory.

  2. Medium:

    Describe the data you'd store for a simple blog (posts, authors, comments) and how the pieces relate.

  3. Hard:

    Explain what could go wrong if two users buy the last item in stock at the same moment, and how a database might prevent it.

Interview questions

Why can't an application just keep all its data in server memory?

Memory is wiped when a process restarts or crashes, and it isn't shared across servers. A database gives durable, shared storage.

What's the difference between reading and writing data in terms of design concerns?

Reads are usually far more frequent and easier to scale (with caching or replicas). Writes need stronger guarantees around consistency and conflicts.

What is data persistence?

Data surviving beyond the process that created it, for example still being there after a server restarts.

What does ACID stand for, and why does it matter for a transaction?

Atomicity, Consistency, Isolation, Durability. A transaction applies fully or not at all, leaves data valid, doesn't interfere with other concurrent transactions, and survives a crash once committed.

Why do multiple statements often need to be grouped into a single transaction, rather than run one at a time?

If a transfer debits one account and credits another in two separate statements, a crash between them could lose money. One transaction guarantees both apply or neither does.

What is a database index, and why isn't every column simply indexed by default?

An index is a separate sorted structure that finds matching rows without scanning the whole table. But every index must be updated on every write and takes its own storage, so indexing everything slows writes for little gain on rarely queried columns.

Mechanically, why does an index make a lookup fast where scanning the whole table wouldn't?

Most indexes are B-trees, sorted structures the database can binary-search. A match takes roughly log(n) steps whatever the table size, instead of a full scan checking all n rows.

What's the difference between optimistic and pessimistic concurrency control?

Pessimistic control locks a row upfront so no other transaction can touch it. Optimistic control lets transactions run freely and checks at commit time whether the data changed, retrying if so. Optimistic is better when conflicts are rare.

What is a deadlock, and how does a database typically handle it?

Two transactions each hold a lock the other needs, so neither can continue. The database detects the cycle and aborts (rolls back) one of them.

What does normalizing a schema mean, and what's the tradeoff of deliberately denormalizing it?

Normalizing splits data across tables so each fact is stored once, keeping it consistent by design. Denormalizing duplicates data for faster reads (fewer joins), but every copy must be kept in sync on writes.

What is the N+1 query problem, and how do you fix it?

Fetching N records, then running one extra query per record in a loop for related data: 1 + N queries where one would do. Fix it by loading the related data in one query (a join, or one WHERE id IN (...) batch fetch).

Why can an ORM sometimes hurt performance compared to hand-written SQL?

An ORM hides which queries it actually runs. A chain of object accesses can quietly cause an N+1 pattern or fetch far more rows and columns than needed, and you may not notice until it's slow at scale.

What is connection pooling, and why does it matter?

Opening a database connection costs a TCP handshake and authentication. A pool keeps open connections ready to reuse across requests instead of opening and closing one per request.

What does a query's `EXPLAIN` plan tell you, and when would you reach for it?

It shows how the database plans to run a query: whether it uses an index or scans the table, and the order it joins tables. Check it first when a query is unexpectedly slow.

What's the difference between a primary key and a foreign key?

A primary key uniquely identifies each row in its table. A foreign key stores another table's primary key to represent a relationship, and the database can enforce that the referenced row exists.

What's the difference between OLTP and OLAP databases?

OLTP (Online Transaction Processing) handles many small, frequent reads and writes, like placing an order. OLAP (Online Analytical Processing) runs fewer, much larger queries over lots of historical data for reporting. The workloads differ enough that they're often served by different systems.

Why isn't replication a substitute for backups, even though both involve keeping copies of data?

A replica copies changes as they happen, including a mistaken delete or corruption on the primary. A backup is a separate point-in-time snapshot you can restore from later, which replication doesn't give you.

Scenario: a `products` query filters by `category` and sorts by `price`, and it's slow at 50 million rows despite an index on `category` alone. What's likely happening?

The index finds the category's rows quickly, but the database still has to sort all of them by price, often spilling to disk at that volume. A composite index on (category, price) returns them already sorted. Confirm by checking whether the query plan shows a separate sort step.

What is a "dirty read," and what prevents it?

Reading a row another transaction changed but hasn't committed. It might still be rolled back, so you read data that never really existed. Any isolation level above the weakest (read uncommitted), so read committed and up, prevents it.

What's the difference between a "non-repeatable read" and a "phantom read"?

A non-repeatable read: reading the same row twice in one transaction and getting different values, because another transaction updated it in between. A phantom read: running the same range query twice and getting a different set of rows, because another transaction inserted or deleted matching rows in between.

When would you reach for vertical scaling of a database versus horizontal scaling (replication or sharding)?

Vertical scaling (a bigger server) is simpler, with no distributed-systems complexity, and works up to a point. But it has a hard ceiling, cost rises faster than capacity near the top, and it's still a single point of failure. Horizontal scaling spreads load and risk across machines at the cost of real operational complexity. Use it once the vertical ceiling or single-server risk is the actual constraint.

Scenario: your database's CPU is pegged near 100% during peak hours, mostly from read queries. Name two different fixes and what each costs.

Read replicas spread reads across more machines, at the cost of replication lag and more operations work. A cache in front of the database avoids hitting it for repeat reads, at the cost of sometimes serving slightly stale data. (Scaling vertically is a third option, but only lasts until the next ceiling.)

Why is directly building a SQL query string from user input dangerous, and what's the standard fix?

If input is concatenated into a query, an attacker can craft input that changes its meaning (SQL injection), for example by ending the string early and adding their own clause. The fix is parameterized queries (prepared statements): input is always passed as data and can never become part of the query's structure.

What is a write-ahead log, and why do databases use one?

Before changing data on disk, the database appends the change to a durable, sequential log. If it crashes mid-write, it replays the log on restart to reach a consistent state instead of losing or corrupting data. It's how the "D" (durability) in ACID works.

Scenario: you need to add a `NOT NULL` column to a table with 200 million existing rows, with zero downtime allowed. What has to be handled carefully?

Adding a NOT NULL column with no default in one step on a table that size usually means a long lock or a table rewrite. Safer: add the column as nullable, backfill existing rows in small batches so the whole table isn't locked, then add the NOT NULL constraint once every row has a value.

What's the difference between a database-enforced constraint (like a foreign key or unique constraint) and the same rule checked only in application code?

A database constraint holds no matter what writes the data: a bug, another service, or a race between two concurrent writes can't break it. An app-level check can be bypassed by any other path to the database, and has its own race between the check and the write.