AI database design: schemas, indexes and safe migrations, step by step

AI database design: schemas, indexes and safe migrations, step by step

AI database design works best when you give the model your access patterns and constraints, let it draft the schema, indexes and migrations, and then review the result against a fixed checklist. This guide shows the prompts, the PostgreSQL details AI tools most often get wrong, safe migration patterns and how to give a coding agent database access without risking your data.

In shortTL;DR
  • Describe access patterns, data volume and your database version in the prompt; a schema designed without them is a guess.
  • Review every AI schema for types, NOT NULL, foreign keys, unique constraints and check constraints before any code depends on it.
  • PostgreSQL does not index foreign key columns automatically; ask the AI to list every query and the index that serves it.
  • Use expand and contract migrations, CREATE INDEX CONCURRENTLY, NOT VALID constraints and a lock_timeout so changes don't lock busy tables.
  • Give coding agents a read-only role on a non-production database; never hand them production write credentials.

What can AI database design do, and where does it fail?

AI can do most of the drafting in database design: turning requirements into tables, proposing keys and constraints, suggesting indexes and writing migrations. It cannot know your business rules, data volumes or traffic unless you tell it, and it does not carry responsibility when a migration locks a table at peak hour.

The useful split is draft versus decision:

TaskWhat AI does wellWhat you must check
Schema from requirementsTables, relations, naming, boilerplate columnsBusiness rules, cardinality, what must be unique
Data typesSensible defaults for common casesMoney, time zones, text length limits, IDs
IndexesIndexes for the queries you listQueries you forgot to list, write cost, duplicates
MigrationsCorrect DDL syntax, rollback scriptsLocks on large tables, data backfills, deploy order
QueriesFast, readable SQLPlans on production-sized data, edge cases

The examples below use PostgreSQL, because it is a common default and its documentation is precise about locking. The workflow applies to MySQL, SQLite and others; the specific commands differ.

What should you tell the AI before it designs a schema?

Tell the AI the entities, the access patterns, the expected data volume and your stack, in that order. Access patterns matter most: a schema is good or bad relative to the queries it has to serve, and a model that doesn't know them optimizes for nothing in particular.

prompt
Design a PostgreSQL 17 schema for an invoicing app. Output SQL DDL only, then a short list of assumptions.Entities: organizations, users (belong to one organization), customers, invoices, invoice line items, payments.Rules:- Every row belongs to exactly one organization (multi-tenant, shared tables).- Invoice numbers are unique per organization.- Amounts are in minor units (cents) with an ISO currency code per invoice.- Invoices are never deleted; they move to status "void".Access patterns (most frequent first):1. List an organization's invoices by status, newest first, 50 per page.2. Show one invoice with its line items and payments.3. Sum unpaid totals per customer for an organization.Volume: about 2 million invoices per year across all organizations.Requirements: identity primary keys, timestamptz for times, NOT NULL wherever a value is always present, foreign keys with explicit ON DELETE behavior, check constraints for statuses and non-negative amounts, and one index per access pattern with a comment naming the pattern.

Two habits make the draft better:

  • Ask for assumptions. The list at the end shows you what the model guessed. Wrong guesses are cheaper to fix in the prompt than in a migration.
  • Ask for a second opinion in a fresh session. Paste the DDL back and ask: "Review this schema for missing constraints, wrong types and access patterns it serves poorly." Models catch more in review mode than while generating.

If you work in a coding agent, put the database conventions (naming, ID type, timestamp columns, migration tool) in the project's instructions file so every session follows them. Our guide to CLAUDE.md best practices shows the format.

How do you review an AI-generated schema?

Review an AI schema in a fixed order: types, nullability, keys, constraints, then naming. Most problems in generated schemas are missing constraints, not wrong syntax, because a schema without constraints still runs.

The PostgreSQL community's Don't Do This page lists type mistakes that also show up in AI output:

  • timestamp instead of timestamptz. The wiki recommends timestamptz, which records a single moment in time.
  • serial instead of identity columns. For new applications the wiki says to use identity columns.
  • money for amounts. The wiki says numeric or (rarely) integer may be better.
  • varchar(n) by default and char(n), even for fixed-length codes. Use text, with a check constraint if you need a length rule.

Here is what a reviewed version of part of the invoicing schema looks like:

schema.sql
CREATE TABLE organizations (  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,  name       text NOT NULL,  created_at timestamptz NOT NULL DEFAULT now());CREATE TABLE invoices (  id              bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,  organization_id bigint NOT NULL REFERENCES organizations (id) ON DELETE RESTRICT,  number          text NOT NULL,  status          text NOT NULL DEFAULT 'draft'                  CHECK (status IN ('draft', 'sent', 'paid', 'void')),  currency        text NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),  total_cents     bigint NOT NULL CHECK (total_cents >= 0),  issued_at       timestamptz,  created_at      timestamptz NOT NULL DEFAULT now(),  UNIQUE (organization_id, number));-- Access pattern 1: an organization's invoices by status, newest firstCREATE INDEX invoices_org_status_created_idx  ON invoices (organization_id, status, created_at DESC);

Questions to ask of every table the AI produces:

  1. Which columns can really be empty? Everything else gets NOT NULL.
  2. What must be unique, and unique within what scope (globally, per organization)?
  3. What happens to child rows when a parent is deleted? Choose RESTRICT, CASCADE or SET NULL on purpose.
  4. Which values have a fixed set or range? Encode it in a CHECK or a lookup table.
  5. In a multi-tenant schema, does every tenant-owned table carry the tenant ID, and do unique constraints include it?

How do you choose indexes with AI help?

Ask the AI to map every frequent query to the index that serves it, then remove indexes no query needs. Indexes speed up reads but slow down every write and take space, so "index everything" is as wrong as "index nothing".

One detail models often miss: the PostgreSQL constraints docs say that declaring a foreign key "does not automatically create an index on the referencing columns". Without one, deleting or updating a parent row has to scan the child table. In the schema above, the unique constraint on (organization_id, number) already starts with organization_id, so it covers that foreign key; a separate index on organization_id alone would be redundant.

Then check the plan on realistic data. EXPLAIN ANALYZE shows the real row counts and timings, but the EXPLAIN docs warn that with ANALYZE the statement actually runs, so wrap writes in a transaction you roll back:

check a plan
BEGIN;EXPLAIN (ANALYZE, BUFFERS)UPDATE invoices SET status = 'void' WHERE organization_id = 42 AND number = 'INV-1001';ROLLBACK;

On a running system, let the database tell you which queries matter. The pg_stat_statements extension tracks planning and execution statistics for all statements; it must be added to shared_preload_libraries, which needs a server restart. Paste its top queries into the AI and ask for index suggestions:

top queries by total time
SELECT query, calls, mean_exec_time, total_exec_timeFROM pg_stat_statementsORDER BY total_exec_time DESCLIMIT 10;

How do you write safe migrations with AI?

Ask the AI for migrations that never take a long, blocking lock on a busy table, and tell it the table sizes. A migration that is correct SQL can still take an application down if it rewrites a large table or waits behind a long query while every other request queues behind it.

The PostgreSQL behaviors to put in your prompt, each from the official docs:

ChangeRiskSafer pattern
ADD COLUMN with a constant defaultFast: the default is stored in metadata, no rewrite (ALTER TABLE)Fine as is
ADD COLUMN with a volatile default such as clock_timestamp()Rewrites the whole table and its indexesAdd the column empty, backfill in batches
SET NOT NULL on an existing columnScans the whole table under a strong lockAdd a CHECK (col IS NOT NULL) NOT VALID, validate it, then set NOT NULL
New foreign key or check constraintScans the table to verify existing rowsAdd it NOT VALID, then VALIDATE CONSTRAINT (takes a weaker SHARE UPDATE EXCLUSIVE lock)
CREATE INDEXBlocks writes until the build finishesCREATE INDEX CONCURRENTLY (cannot run inside a transaction block)
Any DDL on a busy tableWaits for a lock while new queries queue behind itSET lock_timeout and retry

An expand and contract migration for adding a required column looks like this:

migration: add a required due_at column
SET lock_timeout = '5s';-- 1. Expand: add the column without a default rewriteALTER TABLE invoices ADD COLUMN due_at timestamptz;-- 2. Backfill in batches from application code or a script, e.g.:-- UPDATE invoices SET due_at = coalesce(issued_at, created_at) + interval '30 days'-- WHERE id BETWEEN 1 AND 10000 AND due_at IS NULL;-- 3. Enforce without a long lockALTER TABLE invoices  ADD CONSTRAINT invoices_due_at_present CHECK (due_at IS NOT NULL) NOT VALID;ALTER TABLE invoices VALIDATE CONSTRAINT invoices_due_at_present;ALTER TABLE invoices ALTER COLUMN due_at SET NOT NULL; -- skips the scan: the valid CHECK proves no NULLsALTER TABLE invoices DROP CONSTRAINT invoices_due_at_present;
migration: index without blocking writes
-- Must run outside a transaction; most migration tools have a per-migration switch for thisCREATE INDEX CONCURRENTLY invoices_due_at_idx ON invoices (due_at);

Deploy order matters as much as SQL. Ship the expand migration, then code that writes the new column, then the backfill, then the constraint, and remove old columns only after no running code reads them.

Warning

Migration generators are drafts too. The Alembic docs say autogenerate "is not intended to be perfect" and that it is always necessary to manually review and correct the migrations it produces. The same goes for migrations an AI writes.

How do you get AI to write good SQL queries?

Give the AI the exact DDL of the tables involved and say what the query is for and how often it runs. A model that sees real column names and constraints writes correct joins far more often than one working from a description.

Rows of server racks in a data center
A query that is instant on a laptop can scan millions of rows in production.

Rules that catch most problems:

  • Test with production-sized data. A sequential scan is invisible on 500 rows.
  • Ask for the index each query relies on. If the answer is "none", decide whether that is acceptable.
  • Watch for N+1 patterns in ORM code: one query per row inside a loop. Ask the AI to rewrite them as a single join or a batched IN query.
  • Check NULL handling and time zones in filters and aggregates; they are where plausible-looking SQL returns wrong numbers.

Our guide to AI for SQL covers query writing in more depth, and writing tests with AI shows how to pin query behavior down with tests.

How do you give a coding agent safe database access?

Give a coding agent a local or staging database and, when it needs to inspect real data, a read-only role. An agent with production write credentials can drop or corrupt data through a simple mistake or an instruction hidden in content it reads.

PostgreSQL's predefined roles make a read-only user short. pg_read_all_data grants read access to all tables, views and sequences (it does not bypass row-level security):

read-only role for an agent
CREATE ROLE agent_ro LOGIN PASSWORD 'change-me';GRANT pg_read_all_data TO agent_ro;ALTER ROLE agent_ro SET default_transaction_read_only = on;

The grant is the real boundary; default_transaction_read_only is only a default that a session can change, so treat it as a second layer, not the protection itself. For anything sensitive, point the agent at a copy with personal data removed.

Where the agent runs matters as well. Running it on a separate machine with its own development database keeps a bad command away from your laptop and your production credentials. Our guide to sandboxing AI coding agents compares containers, VMs and remote servers. Orkio is one option: an always-on cloud server, isolated from other customers, where agents such as Claude Code work in your repository and open pull requests, so schema and migration changes reach you as a reviewable diff.

AI database design review checklist

Run this checklist on every AI-generated schema change before it merges. Paste it into your pull request template or give it to a reviewing agent along with the diff, as described in our guide to AI code review.

review checklist
Schema[ ] Types: timestamptz for times, identity IDs, text (not varchar(n)/char(n)) unless a limit is a rule, integer cents or numeric for money[ ] NOT NULL on every column that always has a value[ ] Primary key on every table; unique constraints for natural keys, scoped per tenant[ ] Foreign keys with deliberate ON DELETE behavior[ ] CHECK constraints for statuses, ranges and formatsIndexes[ ] Every frequent query maps to an index (or a documented decision not to index)[ ] Foreign key columns are indexed, or covered by a multi-column index that starts with them[ ] No duplicate or unused indexesMigrations[ ] Table sizes known; no full-table rewrite or long lock on large tables[ ] lock_timeout set; CREATE INDEX CONCURRENTLY outside a transaction[ ] New constraints added NOT VALID, then validated[ ] Backfills batched and restartable[ ] Deploy order written down (expand, code, backfill, enforce, contract)[ ] Tested on a copy of production-sized data; rollback path knownAccess[ ] Agents and tools use non-production databases or read-only roles

How to start today

Pick one table you plan to add this week and run it through the loop.

  1. Write the access patterns and rules in the prompt format above and ask for DDL plus assumptions.
  2. Review the draft with the checklist, then ask a fresh AI session to critique it.
  3. Ask for the migration with the table size stated, and test it on a copy of real data.
  4. Run EXPLAIN (ANALYZE, BUFFERS) on the two most frequent queries.
  5. Merge through a normal pull request review, and add the conventions you settled on to your project instructions so the next AI session starts from them.

Frequently asked questions

Can ChatGPT or Claude design a database schema?

Yes, current models produce reasonable first drafts of relational schemas, including tables, keys, constraints and indexes, especially when you describe the entities and the queries the app will run. They still miss business rules they were not told about and sometimes pick weak types or skip constraints. Treat the output as a draft that a person reviews.

Should I let an AI agent run migrations on production?

No. Let the agent write and test migrations against a local or staging database, then apply them to production through your normal deploy pipeline after review. Production credentials with write access give a mistaken or manipulated agent the power to destroy data.

What information should I give AI to design a database?

Give it the entities and how they relate, the most frequent reads and writes, rough row counts, the database engine and version, your ORM or migration tool, and rules such as uniqueness, soft deletes, multi-tenancy and retention. The more of these you state, the fewer silent assumptions the model makes.

Is AI good at writing SQL queries?

AI is good at writing correct SQL for well-described schemas, and it is fast at turning a question into a query. Check the results on real data, look at the plan with EXPLAIN for anything that runs often, and watch for queries that work on a small test database but scan whole tables in production.

Which database should I use with AI coding tools?

Any mainstream database works, but PostgreSQL is a common default because models have seen a lot of it, its documentation is thorough and it supports features like transactional DDL and concurrent index builds. Choose the database for your workload first; the AI will adapt.

SOURCES

  1. PostgreSQL docs: CREATE INDEX (Building Indexes Concurrently)
  2. PostgreSQL docs: ALTER TABLE
  3. PostgreSQL docs: Constraints
  4. PostgreSQL docs: Using EXPLAIN
  5. PostgreSQL docs: pg_stat_statements
  6. PostgreSQL docs: Predefined roles
  7. PostgreSQL wiki: Don't Do This
  8. Alembic docs: Auto Generating Migrations
  • #database design
  • #postgresql
  • #migrations
  • #ai coding
Orkio team

The team building Orkio. We write about putting AI to work: coding agents that run overnight, always-on boxes and pull requests ready by morning.

Keep reading

All posts

07:06 · YOU MERGED #128

Go to sleep. Wake up to pull requests.

Start for $19 a month
© 2026 Orkio · Hosted in Europe TürkçeStatus