Database Queries & Migrations

Prompt queries and migrations with the real schema, the engine, and safety rules so you avoid slow, wrong, or destructive SQL.

TL;DR

  1. Give the real schema and the exact engine; SQL dialects and ORM APIs differ in ways that matter.
  2. Require parameterized queries and never interpolate user input into SQL.
  3. Treat migrations as high-risk: reversible, reviewed, and tested on a copy before production.

Ground In Schema

    Paste The Tables

    Give column names, types, and relations so queries are valid.

    orders(id, user_id FK, status,
    total_cents, created_at)
    Name The Engine

    State Postgres, MySQL, SQLite, and the version.

    "PostgreSQL 16" (not just "SQL")
    Show The Indexes

    List indexes so the model writes queries that use them.

    idx_orders_user_id,
    idx_orders_created_at

Safe Queries

    Parameterize

    Demand bound parameters, never string interpolation.

    WHERE user_id = $1   -- not + userId
    Use The ORM Safely

    Prefer the query builder's safe API over raw string building.

    db.order.findMany({ where:
    { userId } })
    Least Data

    Select only needed columns; avoid SELECT * in app queries.

    "Select id, status, total_cents only."

Performance

    Index Awareness

    Ask which index a query uses and whether it is sargable.

    "Which index serves this WHERE?
    Is it a range or full scan?"
    Avoid N+1

    Request joins or batched loads instead of per-row queries.

    "Fetch orders with their items in
    one query, not per order."
    Verify With EXPLAIN

    Confirm the plan against the real database, not the model's claim.

    EXPLAIN ANALYZE <query>

Migrations With Care

    Reversible

    Ask for both an up and a down migration.

    "Provide up and down; down must
    restore the prior state."
    Avoid Locks

    Flag operations that lock large tables and request safe alternatives.

    "Add the column nullable first;
    backfill in batches."
    Test On A Copy

    Run on a snapshot before production; back up first.

    Dry-run on a copy. Backup.
    Then apply.

Tips

  1. Paste the table definitions and indexes so the model writes queries that use them.
  2. Ask for the query plan reasoning ('which index does this use?') when performance matters.

Warnings

  1. String-interpolated SQL is an injection hole; demand parameterized queries or the ORM's safe API.
  2. Migrations can destroy or lock data; never run a model's migration on production unreviewed and unbacked-up.

In Practice

FAQ