# How to design the database for an internal tool: the patterns that recur in our schemas

Source: https://personalsoftwarefactory.com/guides/database-design-for-internal-tools
Updated: 2026-12-05

> The database design patterns that keep coming back in the internal tool schemas on Personal Software Factory: integer money, status checks, computed values, copies, append-only logs, unique keys, child tables and delete rules, with real SQL that runs on SQLite and PostgreSQL.

## The short answer

Write the data model down first, then let the database refuse everything that one row or one unique key can refuse, and name every other rule as something the app must enforce. When we turned our blueprints' data models into SQL, the same decisions came back in schema after schema: money and durations are integers in the smallest unit; a status is a fixed list, and the fields that belong to a status are checked against it; anything that depends on other rows or on today is computed, not stored; values that must not change later are copied onto the record; history goes into logs that are only ever added to; unique keys make a repeated job, a double booking or a second "open" row fail at the insert; lists get their own tables; and every foreign key has a deliberate answer to "what happens when the parent is deleted".

Every pattern below comes from the schemas on [/schemas](/schemas). Each of those is SQL written from the data model in one of our [blueprints](/blueprints), run unchanged on SQLite 3.53.4 and PostgreSQL 19.0 (PGlite 0.6.1) and loaded with that blueprint's seed data. The excerpts are copied from those files. MySQL and other versions were not tested.

## 1. Money, durations and percentages are integers in the smallest unit

**What it is.** Amounts are stored as integer cents, percentages as integer basis points (7.5% is 750) and durations as integer minutes or half-days. There is no decimal or floating-point column for any of them.

**Why.** The specs say so. The approval workflow stores amounts as integer cents in one currency (section 3 and rule R6). The quote builder stores cents and basis points (R1). The time-off tracker stores every day amount as half-days, so one day is 2 (section 5). Timesheets store minutes in 15-minute steps (R1).

From `timesheets.sql` and `quote-builder.sql`:

```sql
  minutes INTEGER NOT NULL CHECK (minutes BETWEEN 15 AND 1440 AND minutes % 15 = 0),
```

```sql
  discount_bp INTEGER NOT NULL DEFAULT 0 CHECK (discount_bp BETWEEN 0 AND 10000),
```

**Where it is used.** [Approval workflow](/schemas/approval-workflow), [Quote builder](/schemas/quote-builder), [Time-off tracker](/schemas/pto-tracker), [Timesheets](/schemas/timesheets).

**What goes wrong without it.** The quote builder decides whether a discount needs approval by comparing integers, so exactly 15.0% does not need approval and 15.5% does; floating-point percentages make that boundary unreliable. In the time-off tracker, decimal days invite rounding errors in balance sums. In timesheets, decimal hours would let 1.33 h through and make sums drift.

**What the build tests found.** The timesheets build found that the form also has to accept typed values, so the CHECK is the last line that refuses an entry like 1:40 ([field report](/blueprints/timesheets#field-report)). The quote builder build found that the approval record stored the discount as whole basis points while the spec says never to round percentages; that column is now for display only, and the approval decision is always the integer comparison ([field report](/blueprints/quote-builder#field-report)).

## 2. A status is a fixed list, and the fields that go with it are checked against it

**What it is.** A status column is `TEXT` with a `CHECK (status IN (...))` that uses the spec's exact values. A second CHECK ties the columns that only make sense in some statuses (who approved, when, a reason, a payment reference) to those statuses, in both directions.

**Why.** Specs define what each status carries. In timesheets, a draft week has no submission data, a submitted week has a submission time and an approver, and an approved week also has who approved it and when. In expense reports, a reimbursed report must have a payment reference, a paid date and a reimbursement time (section 8). In the CRM, won and lost deals have a closed date and only lost deals have a reason (R17).

From `timesheets.sql`:

```sql
  status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'submitted', 'approved')),
  ...
  CHECK ((status = 'draft' AND submitted_at IS NULL AND approver_id IS NULL AND approved_at IS NULL AND approved_by IS NULL)
      OR (status = 'submitted' AND submitted_at IS NOT NULL AND approver_id IS NOT NULL AND approved_at IS NULL AND approved_by IS NULL)
      OR (status = 'approved' AND submitted_at IS NOT NULL AND approver_id IS NOT NULL AND approved_at IS NOT NULL AND approved_by IS NOT NULL))
```

**Where it is used.** [Timesheets](/schemas/timesheets), [Expense reports](/schemas/expense-reports), [Simple CRM](/schemas/simple-crm), [Client onboarding tracker](/schemas/client-onboarding-tracker). The same shape appears in most of the other schemas.

**What goes wrong without it.** In the CRM, a reopened deal could keep its old closed date and still count in Won this month. In expense reports, a report could be marked paid without a reference, or a draft could carry one. With the CHECK, a wrong status update fails in the database, not only in the app.

**What the build tests found.** The timesheets build found that rule R13 never said what rejecting a week or withdrawing an approval clears. The spec now says both clear the submission time and the approver, and withdrawing also clears who approved and when, which is exactly what the CHECK above expects ([field report](/blueprints/timesheets#field-report)).

## 3. Anything that depends on other rows or on today is computed, not stored

**What it is.** Balances, overdue flags, warranty states, expense flags and "trust" labels have no column. They are worked out from the rows each time they are shown.

**Why.** The specs say so directly. The time-off tracker computes balances from the rows every time (R7 and section 7). The CRM computes overdue, due today and upcoming by comparing the next follow-up date with today (R2, section 10). The equipment tracker's Expired, Ending soon and Covered depend on today and a notice setting (R7).

From `pto-tracker.sql`, the allowance table holds only the inputs:

```sql
-- App rule (R7): balances are computed from requests every time; no running total is stored.
CREATE TABLE allowances (
  id TEXT PRIMARY KEY,
  person_id TEXT NOT NULL REFERENCES people(id),
  year INTEGER NOT NULL,
  entitlement INTEGER NOT NULL CHECK (entitlement >= 0), -- half-days
  carried_over INTEGER NOT NULL DEFAULT 0, -- half-days, may be negative; written only when the previous year is closed
  adjustment INTEGER NOT NULL DEFAULT 0, -- half-days, may be negative
```

**Where it is used.** [Time-off tracker](/schemas/pto-tracker), [Simple CRM](/schemas/simple-crm), [Equipment tracker](/schemas/equipment-tracker), [Expense reports](/schemas/expense-reports). The capacity planner, the knowledge base, the customer feedback inbox and the content calendar make the same choice.

**What goes wrong without it.** A running balance that each action adds to and subtracts from drifts as soon as one action fails halfway, and then the person and the system disagree. A stored overdue status is wrong the morning after it was written, because nothing writes to the row when the date passes.

Some values are stored on purpose, and the schema says why. The quote builder stores its totals so lists don't recompute them, and the server recomputes them on every save (R2). The help desk stores the first-response due time so the queue can sort by it and the deadline stays fixed once an agent has replied (R5).

**What the build tests found.** The expense reports build found it unclear when flags are computed; the spec now says they come from current data whenever an expense or report is shown ([field report](/blueprints/expense-reports#field-report)). The equipment tracker build found the warranty end date itself was unclear: on that date an item is Ending soon, and the day after it is Expired ([field report](/blueprints/equipment-tracker#field-report)).

## 4. Values that must not change later are copied onto the record

**What it is.** When a later change somewhere else must not rewrite a record, the record keeps its own copy: the product name and price on a quote line, the hourly rate on an approved time entry, the question text on a standup answer, a whole statement on an approved commission period.

**Why.** The quote builder copies the product's name, unit and price when a line is added, so a later price change never touches an existing quote (R3, R15). Timesheets copy the project's rate onto entries when a week is approved (R9). The time-off tracker freezes the day count on the request at creation (R12).

From `quote-builder.sql` and `async-standups.sql`:

```sql
  name TEXT NOT NULL, -- copied from the product when added
```

```sql
  question_text TEXT NOT NULL, -- copied when saved
  kind TEXT NOT NULL CHECK (kind IN ('text', 'choice', 'blocker')), -- copied when saved
```

**Where it is used.** [Quote builder](/schemas/quote-builder), [Timesheets](/schemas/timesheets), [Async standups](/schemas/async-standups), [Sales commission calculator](/schemas/commission-calculator). The time-off tracker, employee onboarding, the client onboarding tracker and the link shortener copy values the same way.

**What goes wrong without it.** In timesheets, a rate change to $160 would reprice Lee's week that was approved at $150. In the time-off tracker, adding a public holiday would silently change past balances.

**What the build tests found.** In the commission calculator build, calculating an already approved August live left out deal #1002, which was cancelled after approval, and gave $8,860 instead of $10,060. Reading approved statements from the snapshot taken at approval avoids that ([field report](/blueprints/commission-calculator#field-report)). Async standups copy the question because a question's text, required flag and options can change after it has answers (section 5); that build found the seed didn't say what text a blocker answer stores, and it is now the section 8 text ([field report](/blueprints/async-standups#field-report)).

## 5. History is a log that is only ever added to

**What it is.** Changes are written as new rows in an events, status change, movement or assignment table, and those rows are never edited or deleted. Current state is either computed from the log or stored next to it, but the log is the record.

**Why.** The inventory tracker makes the movement log the source of truth: stock on hand is the sum of movements, and movements are never edited or deleted (section 5, R2). The status page computes uptime and each day's bar only from its status log (R2). The approval workflow writes exactly one event per action and never edits one (R5).

From `inventory-tracker.sql`:

```sql
-- One change to the quantity of one item at one location. Append-only: never edited or deleted (R2).
-- On hand at a location is the sum of its movements. App rule (R1): no movement may take a location below zero.
CREATE TABLE movements (
  id TEXT PRIMARY KEY,
  at TIMESTAMP NOT NULL, -- count movements are dated at approval
  item_id TEXT NOT NULL REFERENCES items(id),
  location_id TEXT NOT NULL REFERENCES locations(id),
  quantity INTEGER NOT NULL, -- positive in, negative out, in the item's unit
```

**Where it is used.** [Inventory tracker](/schemas/inventory-tracker), [Status page](/schemas/status-page), [Approval workflow](/schemas/approval-workflow), [Equipment tracker](/schemas/equipment-tracker), where each period someone holds an item is its own row.

**What goes wrong without it.** The approval workflow stores each step of the chain as a row per round instead of working the chain out from the rules when it is shown; a schema that computes it at read time shows a different history after every rule change. Portable SQL cannot forbid updates without triggers, which these schemas avoid, so "never edited" is a comment on the table and a property of the app: give it no code path that updates or deletes a log row.

**What the build tests found.** The status page build found the spec didn't say what a component's status was before its first log row, so every component now gets an operational row when it is created ([field report](/blueprints/status-page#field-report)). The equipment tracker build found that sending an assigned item to repair didn't say what it records; the repair note is now the closed assignment's condition ([field report](/blueprints/equipment-tracker#field-report)).

## 6. Unique keys make a repeat impossible

**What it is.** A unique key on the thing that must happen once: one reminder per invoice per step, one daily run per date, one digest per person per day, one half-day of leave per person per session, one status update per project per week. The same idea keeps settings to one row, with a primary key that can only be 1.

**Why.** The invoice reminder spec says each invoice gets each step at most once, enforced as a unique row (R2). The time-off tracker's unique key on person, date and half-day is what R5 asks for. The project status board allows one update per project per week, enforced by the database (R3).

From `pto-tracker.sql`:

```sql
  half TEXT NOT NULL CHECK (half IN ('am', 'pm')),
  UNIQUE (person_id, date, half) -- makes double booking impossible (R5)
```

```sql
  id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), -- always 1, so there can only be one row
```

**Where it is used.** [Invoice reminders](/schemas/invoice-reminders), [Time-off tracker](/schemas/pto-tracker), [SaaS spend tracker](/schemas/saas-spend-tracker), [Simple CRM](/schemas/simple-crm). Async standups, employee onboarding and the project status board use the same kind of key for their scheduled jobs and weekly updates.

**What goes wrong without it.** A check in code ("has this been sent?") followed by an insert lets two runs at the same moment both pass the check. With the key, the second insert fails: a doubled reminder run cannot chase a customer twice, two overlapping requests for the same person cannot both be saved, and the SaaS spend tracker's dedupe key means two overlapping job runs cannot queue the same renewal reminder.

**What the build tests found.** The invoice reminders build found that nothing recorded that the day's run had happened, which "safe to run twice" depends on. The fix is a daily run row with a unique date, written in the same transaction as the run's emails ([field report](/blueprints/invoice-reminders#field-report)).

## 7. Partial and case-insensitive unique indexes say exactly which rows must be unique

**What it is.** A unique index with a `WHERE` clause limits uniqueness to some rows: one active step per request, one open assignment per item, one open or submitted count per location, a name that is unique only among tools that are not cancelled. A unique index on `lower(name)` makes names unique ignoring case. Both engines ran these unchanged.

**Why.** The approval workflow allows one active step at a time (section 3), and section 13 needs the second of two simultaneous approvals to fail. The SaaS spend tracker lets a cancelled tool's name be reused (R13). The CRM makes emails and company names unique ignoring case (section 5).

From `approval-workflow.sql`, `equipment-tracker.sql` and `saas-spend-tracker.sql`:

```sql
CREATE UNIQUE INDEX steps_one_active_idx ON steps (request_id) WHERE status = 'active';
```

```sql
CREATE UNIQUE INDEX assignments_one_open ON assignments (item_id) WHERE checked_in_at IS NULL; -- at most one open assignment per item
```

```sql
CREATE UNIQUE INDEX tools_current_name_unique ON tools (LOWER(name)) WHERE status IN ('active', 'cancelling'); -- R13: a cancelled tool's name can be reused
```

**Where it is used.** [Approval workflow](/schemas/approval-workflow), [Equipment tracker](/schemas/equipment-tracker), [SaaS spend tracker](/schemas/saas-spend-tracker), [Inventory tracker](/schemas/inventory-tracker). Case-insensitive name indexes are in most of the schemas.

**What goes wrong without it.** A plain `UNIQUE` is too strong or too weak. On blockers in async standups it would forbid a second resolved blocker, when the rule is only one open blocker. On names it compares case, so "Blog" and "blog" can both exist.

**What the build tests found.** The inventory tracker build found that only an open count blocked a new count at the same location, so a submitted count awaiting review didn't, and approving both would correct the same stock twice. The partial index now covers open and submitted counts ([field report](/blueprints/inventory-tracker#field-report)). The async standups build found a gap in the one-open-blocker rule for a blocker opened while the form was loaded; the partial index is what makes that case fail safely ([field report](/blueprints/async-standups#field-report)).

## 8. Lists get their own table

**What it is.** When the spec gives a field that is a list (a template's weekdays, the components an incident update sets, a customer's email domains, a card's tags), it becomes a child table with one row per item, and its key stops an item repeating.

**Why.** The screens and rules filter and join on the items. The status page emails subscribers of every component that any published update of an incident has set (R9). The customer feedback inbox lets each email domain belong to at most one customer (section 5).

From `shift-scheduling.sql`:

```sql
-- The weekdays a template applies to (the spec's weekdays list).
-- App rule (section 5): a template has at least one weekday.
CREATE TABLE template_weekdays (
  template_id TEXT NOT NULL REFERENCES templates(id) ON DELETE CASCADE,
  weekday INTEGER NOT NULL CHECK (weekday BETWEEN 1 AND 7), -- 1 is Monday, 7 is Sunday
  PRIMARY KEY (template_id, weekday)
);
```

**Where it is used.** [Shift scheduling](/schemas/shift-scheduling), [Status page](/schemas/status-page), [Customer feedback inbox](/schemas/feedback-inbox), [Inspections](/schemas/inspections). The knowledge base, async standups and feature requests do the same.

**What goes wrong without it.** In the feedback inbox, a comma-separated column could not stop two customers claiming the same domain. There is one deliberate exception: the time-off tracker keeps working days as text such as `'1,2,3,4'`, because a child table would move its default and its at-least-one-day rule out of the table and into app code.

**What the build tests found.** The shift scheduling build found that a template's weekdays were described only as "list", with no type ([field report](/blueprints/shift-scheduling#field-report)). The status page build found the subscriber rule had first been read as covering only the latest update's components; with a child table the full rule is one join ([field report](/blueprints/status-page#field-report)).

## 9. Every foreign key has a deliberate delete rule

**What it is.** For each reference, the schema decides what deleting the parent does: delete the children too (`ON DELETE CASCADE`), keep the child and clear the link (`ON DELETE SET NULL`), refuse the delete (no action), or keep the column with no foreign key at all so a log can outlive the row it describes. Some records are never deleted: they are cancelled or archived with a timestamp.

**Why.** The spec says what each delete means. The help desk removes a requester's tickets, messages and outbox rows when the requester is deleted (R14). Async standups delete a removed member's open check-ins but keep their notification rows (R4, section 5). Shift scheduling never deletes events but lets a manager delete a shift with no request history (R9, section 7).

From `help-desk.sql`, `async-standups.sql` and `shift-scheduling.sql`:

```sql
  requester_id TEXT NOT NULL REFERENCES requesters(id) ON DELETE CASCADE, -- R14 removes a requester's tickets
```

```sql
  check_in_id TEXT REFERENCES check_ins(id) ON DELETE SET NULL, -- cleared when R4 deletes the check-in; the row stays
```

```sql
  shift_id TEXT, -- no foreign key: events outlive deleted shifts
```

**Where it is used.** [Help desk](/schemas/help-desk), [Async standups](/schemas/async-standups), [Shift scheduling](/schemas/shift-scheduling), [OKR tracker](/schemas/okr-tracker). The SaaS spend tracker never deletes a tool, and the project status board archives a project with a timestamp rather than a flag, so it knows from which week to show Archived.

**What goes wrong without it.** A foreign key from shift events to shifts would block every allowed shift delete; a cascade would delete the audit trail with it. In the OKR tracker, a team objective's link to a company objective has no delete action on purpose, so the database refuses to delete a company objective that others align to (R6).

**What the build tests found.** The async standups build found that nothing said what happened to outbox rows when a check-in was deleted; `SET NULL` is the fix ([field report](/blueprints/async-standups#field-report)). The OKR tracker build found the spec had not said whether objectives and key results could be deleted or what happened to their check-ins; check-ins and target changes now keep a plain key result column so they survive the delete ([field report](/blueprints/okr-tracker#field-report)).

## What the database cannot enforce

Portable SQL can check one row and one unique key. It cannot check rules that compare a row with other rows, follow a state machine from one status to the next, or depend on who is asking. The schemas keep those out of the DDL and name each one in a comment that starts with `App rule`, so whoever builds the app sees it next to the table it belongs to. Three examples:

```sql
-- App rule (R11): reporting lines cannot loop; reject a manager change that makes someone their own manager, directly or indirectly.
```

That line is in `approval-workflow.sql`. The approval workflow build test found that the admin screen allowed reporting loops, which breaks routing; R11 was added to the spec after it ([field report](/blueprints/approval-workflow#field-report)).

```sql
-- On hand at a location is the sum of its movements. App rule (R1): no movement may take a location below zero.
```

In the inventory tracker, the app must check and write in one transaction, so two people taking the last unit cannot both succeed.

```sql
-- App rule (R1): the total of a person for one date is at most 1,440 minutes, and dates cannot be after today.
```

That is from `timesheets.sql`: each entry is checked by the table, but the daily total spans rows.

The database can still give the app what it needs. For edits that two people (or a person and a scheduled job) might make at once, the [Help desk](/schemas/help-desk) and [SaaS spend tracker](/schemas/saas-spend-tracker) schemas have a `version` column that goes up on every change. The app sends the version it showed and refuses the write when the row has moved on. The column is in the schema; the comparison is an app rule.

## SQLite and PostgreSQL differences that mattered

Only the differences the schema work actually ran into:

- **INTEGER is 32-bit in PostgreSQL and 64-bit in SQLite.** In the [Sales commission calculator](/schemas/commission-calculator), a $58,000 tier slice in cents times 1,000 basis points overflows on PostgreSQL. The spec's $10,000,000 deal cap keeps stored values in range, and the tier math runs in the app or in `BIGINT`. The [OKR tracker](/schemas/okr-tracker) stores values in hundredths, so they must stay within about 21.4 million units.
- **Booleans come back differently.** SQLite returns 0 and 1, PGlite returns true and false. PGlite also returns `DATE` and `TIMESTAMP` values as JavaScript Date objects and `NUMERIC` as strings. Comparing query results across the two engines needed those normalized, and one schema thread selected its booleans as text so results matched exactly.
- **Reserved words.** `to` is reserved in PostgreSQL, so the async standups outbox stores the spec's `to` field as `to_address`, and feature requests store a status change's `from` and `to` as `from_status` and `to_status`.
- **A reference to a table that does not exist yet.** PostgreSQL will not create it. Where two tables point at each other (a request and its current step, a quote and its invoice, a team and its lead), the schemas keep the foreign key on one side and leave the other as a plain column with a comment, as in the approval workflow, the quote builder, the testimonial wall and the OKR tracker.
- **Date arithmetic and rounding.** Date functions differ between the engines, so date math (a renewal notice deadline, whether a date is a Monday, uptime) stays in the app, and the example queries compare with literal dates. In the quote builder, rounding is per step and half up, which plain SQL division does differently on SQLite and PostgreSQL, so that math lives in one app function.
- **No JSON type.** A JSON column is not portable, so event data and the commission calculator's approval snapshot are JSON stored in a `TEXT` column.

## Using a schema with an AI builder

1. **Give the builder the blueprint and the schema together.** The blueprint has the rules, screens, phase prompts and acceptance checks; the schema has the tables. Each schema page links to its blueprint, and each blueprint with a schema links to it under its Data model heading.
2. **Make the schema the source of truth for names.** Tell the builder to use the schema's table and column names exactly, including the ones it renamed from the spec, such as `to_address`. Then the rules, the queries and your own reading of the data all match.
3. **Load the seed data.** Each schema has a seed file with the blueprint's seed data, and each schema page shows how to load it. The acceptance checks are written against that data, so start each phase's checks from a fresh load.
4. **Build the app rules in server code.** Ask the builder to implement every `App rule` comment on the server, and to say which ones it did not get to.
5. **Run the acceptance checks.** After each phase, run that phase's checks from the blueprint in a browser. Passing them is what tells you the builder read the spec the way it was meant.

For the method behind the phases and checks, see [How to build an internal tool with AI](/guides/how-to-build-internal-tools-with-ai); for using a blueprint inside a particular tool, see [how to use the blueprints in Claude, ChatGPT or Cursor](/guides/use-blueprints-in-claude-chatgpt-cursor). Test builds often use SQLite on one machine; in production, use your platform's managed database with the same schema.

## Where to go next

- [All schemas](/schemas): the SQL, seed data, design decisions and example queries for each tool.
- [All blueprints](/blueprints): the specs the schemas are written from, with their build-test field reports.
- [How we test](/how-we-test): what "build-tested" covers, and what it does not.
