---
title: Databases
summary: Where your app's data lives, and how to choose, model and query it.
section: data
phase: design
order: 1
last_reviewed: 2026-11-20
---

# Databases

The database is your app's source of truth and its longest-lived decision. Code can be rewritten in an afternoon. Data models get stuck with you.

> **Sub-pages:** [Schema & migrations](/docs/data/schema-and-migrations.md) · [Backups & recovery](/docs/data/backups-and-recovery.md)

## You'll be able to
- Pick a database type and provider for your project
- Model data with tables, relationships and constraints
- Recognize slow and unsafe query patterns in agent output

## The mental model
A relational database is a set of **tables** (spreadsheets with strict columns) linked by **keys**. You ask questions in **SQL**, and the database works out how to answer them efficiently. It also guarantees that writes are **all-or-nothing** (transactions) and that the rules you declare (constraints) are never broken.

## Key concepts
- **Relational (SQL):** Postgres, MySQL, SQLite. Strict schemas, joins, transactions. **The right default for almost every app.**
- **Document (NoSQL):** MongoDB, Firestore. Flexible JSON documents, which suit nested, rarely-joined data. Postgres `jsonb` covers most of these use cases.
- **Key-value / cache:** Redis, Valkey. Very fast and in-memory. Used for caching, sessions, rate limits and queues, not as the source of truth.
- **Vector databases:** Store embeddings for semantic search and RAG. `pgvector` adds this to Postgres.
- **Primary key:** A row's unique ID (`uuid` or auto-increment `bigint`). **Foreign key:** A reference to another table's row.
- **Relationships:** One-to-many (a user has many posts), many-to-many (posts ↔ tags, via a *join table*).
- **Constraints:** `NOT NULL`, `UNIQUE`, `CHECK`, foreign keys. These let the database enforce correctness, even when the code is buggy.
- **Normalization:** Store each fact once. Denormalize (duplicate data) only on purpose, for speed.
- **Index:** A lookup structure that speeds up reads on a column, at a small cost to writes. Index foreign keys and columns you filter or sort by.
- **Transaction / ACID:** A group of writes that all succeed or all fail. Use one whenever two writes must stay consistent (for example, debiting one account and crediting another).
- **ORM / query builder:** Code-level access to the database (Prisma, Drizzle, SQLAlchemy, Ecto). Convenient, but watch the SQL it generates.
- **N+1 query:** Fetching a list, then running one extra query per item. This is the classic ORM performance bug.
- **Connection pooling:** Reusing database connections. This is essential with serverless functions (PgBouncer, Supavisor, Neon's pooler).
- **SQL injection:** Building SQL by concatenating user input. Always use parameterized queries.

> **Warning:** `EXPLAIN ANALYZE` **executes** the statement to measure it. For a `SELECT` that is harmless. For `INSERT`, `UPDATE` or `DELETE`, the changes really happen, as the PostgreSQL manual points out. To measure a write safely, run it inside a transaction and roll back: `BEGIN; EXPLAIN ANALYZE …; ROLLBACK;`. Do this on a copy of the data, not on production.

## Decisions you make (not the agent)
| Decision | Sensible default | Choose otherwise when… |
|---|---|---|
| Database type | **Postgres** | Embedded/local-first/tiny → SQLite (or Turso). Truly schemaless → document DB |
| Hosting | Managed: Neon, Supabase, RDS, Railway | Strict data residency/cost → self-host |
| Access layer | Drizzle or Prisma (TS), SQLAlchemy (Py) | Complex reporting → raw SQL is fine |
| IDs | UUID (v7 for sortability) or bigint identity | Public-facing IDs → never expose sequential ints |
| Deletes | Hard delete, plus backups | Audit or undo needs → soft delete (`deleted_at`) |
| Timestamps | `timestamptz`, stored in UTC | — |
| Money | Integer cents or `numeric`, **never floats** | — |

### Not sure? Answer a few questions

```decision
title: Pick your database setup
Q: What kind of app is this? | Database type
- A typical web app with users, accounts, orders or bookings -> Postgres | The default for almost every app: strict schemas, joins and transactions.
- A small tool that runs on one machine, in the browser, or ships inside the app -> SQLite (or Turso) | Embedded and local-first apps are where a server database is overkill.
- Records with no fixed structure that you rarely join -> A document database | Truly schemaless data is the case for it. Check you aren't just avoiding schema design.
Q: How will you host it? | Hosting
- I want the least operations work -> A managed service (Neon, Supabase, RDS or Railway) | Managed is the sensible default: backups and upgrades are handled for you.
- Strict data residency rules or hard cost limits -> Self-host | You take on backups, upgrades and monitoring yourself.
Q: Do you need to undo or audit deletions? | Deletes
- No, and I keep backups -> Hard delete, plus backups | Simplest, and a backup covers mistakes.
- Yes (history, undo or an audit trail) -> Soft delete with a deleted_at column | The row stays, so it can be restored or audited.
Q: Will record IDs appear in URLs or APIs that outsiders can see? | IDs
- Yes -> UUIDs (v7 sorts by creation time) | Never expose sequential integers in public-facing IDs.
- No, internal only -> A UUID or a bigint identity column | Either works; choose UUID v7 if you want sortable IDs.
```

## What good output looks like
- Constraints declared in the schema, not just in app code
- Indexes on foreign keys and common filters
- Transactions around multi-step writes
- Every schema change shipped as a migration (see [Schema & migrations](/docs/data/schema-and-migrations.md))

## Red flags
- String-concatenated SQL
- Prices stored as `float`
- No foreign keys, with relations "enforced" by convention only
- `SELECT *` on wide tables in hot paths
- A loop that runs a query on each iteration (N+1)
- A new database connection per request in serverless, with no pooler
- **Common agent mistakes** (several are on the PostgreSQL wiki's "Don't Do This" list): `timestamp` without time zone instead of `timestamptz`; the `money` type instead of `numeric` or integer cents; `serial` columns where identity columns are recommended for new applications; `NOT IN` with a subquery, which returns nothing if the list contains a `NULL` (use `NOT EXISTS`); `BETWEEN` with timestamps, which includes the end boundary

## Worked example

**Task:** Show each order with its customer's name on the admin page.

You prompt: *"List orders with the customer name."* The agent fetches the list of orders, then loops over them and runs one query per order to find the customer. With ten orders it feels instant.

**What a good result contains:** one query that joins orders to customers (or a single eager-loaded fetch), an index on the foreign key, and a check with `EXPLAIN ANALYZE` on that `SELECT`.

**The wrong turn:** this is the N+1 query pattern. The page issues one query for the list and one more for every row, so a thousand orders means about a thousand and one round trips. It is fast in development and slow in production. And when you ask the agent to prove it with timings, it runs `EXPLAIN ANALYZE` on a statement that changes data, and the change really happens.

**How review catches it:** count the queries the page makes (query logging, or the ORM's debug output). If the number grows with the number of rows, it is N+1. Ask for the generated SQL and the plan. Insist that anything measured with `EXPLAIN ANALYZE` that writes data runs in a transaction that is rolled back, on a copy of the data.

## Sample prompts

### Weak vs strong
```compare
## Weak
Set up a database for my app.
## Why it fails
No entities, rules, conventions or important queries, so the agent guesses the schema, and the first thing you learn is what it guessed.
## Strong
Design a Postgres schema (Drizzle ORM, TypeScript) for a booking app.
Entities: users, businesses (owned by a user), services (belong to a business:
name, durationMinutes, priceCents), bookings (user + service + startsAt +
status enum: pending/confirmed/cancelled).
Rules: a service can't have two confirmed bookings that overlap in time;
prices are integer cents; all timestamps timestamptz in UTC; uuid v7 PKs.
Add: foreign keys with sensible ON DELETE behaviour, indexes for "bookings for a
business in a date range" and "a user's upcoming bookings", createdAt/updatedAt.
Output: the schema file, a migration, a seed script, and a short explanation of
each index and constraint. Explain how you'd enforce the no-overlap rule
(exclusion constraint vs app-level check) and pick one.
## Why it works
It states the entities, the business rules, the money and time conventions, the important queries (which drive the indexes), and asks the agent to explain its choices.
## What changed
- **Entities and relationships** are named
- **Business rules** include the no-overlap constraint
- **Conventions** fix money as integer cents and times as `timestamptz` in UTC
- **Queries** that matter are listed, which tells the agent which indexes to add
- **Output** includes an explanation of each index and constraint, so you can check the reasoning
```

```text
Find N+1 queries and missing indexes in this codebase. For each, show the code
location, the queries generated, and the fix. Use EXPLAIN ANALYZE output where
possible.
```
*Why it works:* It asks for locations, the queries generated and the fix together, so each finding is something you can verify.

### Review a schema for the usual mistakes
```text
Review this schema for common PostgreSQL mistakes: timestamps without time zone, the money type, serial instead of identity columns, char(n) or arbitrary varchar limits, missing foreign keys, missing NOT NULL or CHECK constraints, and missing indexes on foreign keys and filter columns. List each finding with the table and column, and the fix. Don't change anything yet.
```
*Why it works:* It targets a known list of mistakes instead of asking for "a review", and a finding per column is easy to verify.

### Measure safely
```text
Show me where this page is slow. Use EXPLAIN ANALYZE only on SELECT statements, and only on the development database. For any statement that changes data, wrap it in BEGIN and ROLLBACK, or explain the plan with plain EXPLAIN instead. Report the query count for one page load, the slowest query, its plan, and your proposed fix. Don't change any code.
```
*Why it works:* It tells the agent the one rule that makes measuring safe: `EXPLAIN ANALYZE` runs the statement.

### Justify every index and constraint
```text
For each index and constraint in this schema, tell me which query or business rule it serves, what it costs (writes, storage) and what would break without it. Mark any that nothing uses, and any business rule that is only enforced in application code.
```
*Why it works:* An index with no query behind it is a cost with no benefit, and a rule enforced only in code is one bug away from bad data.

## Check your understanding

```quiz
Q: You run EXPLAIN ANALYZE UPDATE orders SET status = 'x'. What happens?
- [ ] Nothing: it only shows the plan
- [x] The update runs for real, so wrap it in a transaction and roll back if you only want the timings
- [ ] It is blocked by the database
> Why: ANALYZE executes the statement to measure it. SELECT output is discarded, but writes take effect.

---

Q: Which column type should store a point in time?
- [ ] timestamp (without time zone)
- [x] timestamptz
- [ ] text
> Why: timestamptz stores an actual instant. A plain timestamp is only a calendar reading and gives wrong results across time zones.

---

Q: How can the database itself enforce "no two confirmed bookings for a service may overlap"?
- [ ] A CHECK constraint on the bookings table
- [x] An exclusion constraint, because a CHECK constraint can't look at other rows
- [ ] It can't. Only application code can do this
> Why: PostgreSQL's CHECK constraints can't reference other rows. Cross-row rules use UNIQUE, EXCLUDE or foreign keys.
```

## Checklist
- [ ] Postgres (or a deliberate alternative) chosen
- [ ] Constraints and foreign keys declared
- [ ] Indexes match the real query patterns
- [ ] Money and time stored correctly
- [ ] Backups configured: see [Backups & recovery](/docs/data/backups-and-recovery.md)
- [ ] List pages make a fixed number of queries, not one per row
- [ ] Nothing that changes data is measured with `EXPLAIN ANALYZE` outside a rolled-back transaction

## Go deeper
- [PostgreSQL documentation: Tutorial](https://www.postgresql.org/docs/current/tutorial.html)
- [Use The Index, Luke](https://use-the-index-luke.com)
- [Drizzle ORM docs](https://orm.drizzle.team)
- [PostgreSQL: EXPLAIN](https://www.postgresql.org/docs/current/sql-explain.html): including what ANALYZE executes
- [PostgreSQL wiki: Don't Do This](https://wiki.postgresql.org/wiki/Don%27t_Do_This): common mistakes and their fixes
- [PostgreSQL: Constraints](https://www.postgresql.org/docs/current/ddl-constraints.html): CHECK, UNIQUE, exclusion and foreign keys
- [Building an API](/docs/backend/building-an-api.md): the layer that reads and writes this data
