Databases
Where your app's data lives, and how to choose, model and query it.
11 min read · Last reviewed November 20, 2026
Databases
The database is your app's and its longest-lived decision. Code can be rewritten in an afternoon. Data models get stuck with you.
Sub-pages: Schema & migrations · Backups & recovery
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 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
jsonbcovers 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 .
pgvectoradds this to Postgres. - Primary key: A row's unique ID (
uuidor auto-incrementbigint). 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.
- : 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 / : 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).
- / query builder: Code-level access to the database (Prisma, Drizzle, SQLAlchemy, Ecto). Convenient, but watch the SQL it generates.
- 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 functions (PgBouncer, Supavisor, Neon's pooler).
- SQL injection: Building SQL by concatenating user input. Always use parameterized queries.
Decisions you make (not the agent)#
Your call, not the agent's
| 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#
Pick your database setup
0 of 4 answeredAnswer the questions above and your recommended defaults appear here.
These come from the Decisions table above. Treat them as defaults, not rules.
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)
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):
timestampwithout time zone instead oftimestamptz; themoneytype instead ofnumericor integer cents;serialcolumns where identity columns are recommended for new applications;NOT INwith a subquery, which returns nothing if the list contains aNULL(useNOT EXISTS);BETWEENwith 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#
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.
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
timestamptzin 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
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#
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#
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#
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#
Check your understanding
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
- List pages make a fixed number of queries, not one per row
- Nothing that changes data is measured with
EXPLAIN ANALYZEoutside a rolled-back transaction
Go deeper#
- PostgreSQL documentation: Tutorial
- Use The Index, Luke
- Drizzle ORM docs
- PostgreSQL: EXPLAIN: including what ANALYZE executes
- PostgreSQL wiki: Don't Do This: common mistakes and their fixes
- PostgreSQL: Constraints: CHECK, UNIQUE, exclusion and foreign keys
- Building an API: the layer that reads and writes this data