Command Palette

Search for a command to run...

Back to skills
skill № 70129

backend-database-patterns

Use when the user asks about database schema design, slow queries, indexes, EXPLAIN ANALYZE, N+1 problems, transactions, keyset pagination, connection pooling…

FreeNo executable scripts
j4flmaoby j4flmao★ 47 GitHub stars

Install backend-database-patterns in Claude Code & Claude Desktop

Sign up to install this skill

Create a free account to reveal the install command and save the skill to your library.

  • Reveal the one-line install command
  • Save skills to your synced library
  • Get notified when skills update
Sign up freeI already have an account

About this skill

Backend Database Patterns

Purpose

Design efficient, maintainable database schemas and queries. Every schema change must be backward-compatible. Every query must be verifiable with EXPLAIN ANALYZE.

Agent Protocol

Trigger

Exact user phrases: "database design", "schema design", "query optimization", "slow query", "migration", "index", "ORM pattern", "repository pattern", "N+1 problem", "transaction", "table design", "data model".

Input Context

Before activating, verify:

  • The database type is known (PostgreSQL, MySQL, MongoDB, SQLite).
  • The ORM or query framework is known (TypeORM, Prisma, SQLAlchemy, Diesel, GORM, Spring Data JDBC/JPA).
  • The specific schema, query, or problem is described.

Output Artifact

No file output unless requested. Produces text guidance.

Response Format

Schema design:

## {entity}
| Field | Type | Constraints | Index |
|-------|------|-------------|-------|

Query fix:

## Problem: {description}
Root cause: {specific cause}
Fix: {specific change}
Verification: EXPLAIN ANALYZE {query}

Migration:

## Migration: {description}
Up: {SQL}
Down: {SQL}
Backward-compatible: {yes/no}

Completion Criteria

  • Schema design follows normalization principles (3NF by default).
  • Indexes are specified for every foreign key and filtered column.
  • N+1 queries are identified and fixed.
  • Migration includes up AND down scripts.
  • Migration is verified to be backward-compatible.
  • Transaction boundaries are documented.

Max Response Length

Schema: unlimited. Query fix: 6 lines. Migration: 10 lines.

Architecture Decision Tree

Normalize or Denormalize?

Is the data write-heavy with complex relationships?
  ├── Yes → Normalize (3NF by default)
  └── No → Is there a proven read performance problem (profiled)?
            ├── Yes → Denormalize (with documented trade-offs)
            └── No → Normalize first, optimize later

Primary Key Choice

Is the system single-node with no sharding?
  ├── Yes → BIGSERIAL (auto-increment)
  └── No → Is time-sortable ordering needed?
            ├── Yes → UUID v7 (time-ordered, distributed-safe)
            └── No → UUID v4 (random, distributed-safe)

Index Type Selection

Query pattern:
  ├── Equality lookup (WHERE x = ?) → B-tree
  ├── Range query (WHERE x BETWEEN ? AND ?) → B-tree
  ├── Multi-column filter → Composite B-tree (high-selectivity first)
  ├── Partial subset → Partial index (WHERE status = 'active')
  ├── Full-text search → GIN (tsvector)
  ├── JSON/array containment → GIN (jsonb, @>)
  ├── Geospatial query → GiST (geography, geometry)
  └── All columns in query → Covering index (INCLUDE)

ORM vs Raw SQL?

What is your priority?
  ├── Developer productivity, CRUD-heavy → ORM (Prisma, TypeORM, SQLAlchemy)
  ├── Complex queries, performance-critical → Raw SQL + query builder (kysely, SQLAlchemy core)
  ├── Migration management → ORM migrations or standalone (Alembic, Flyway)
  └── Need both → Repository pattern with ORM for 80%, raw SQL for 20%

Workflow

Step 1: Schema Design

  • Normalize to 3NF by default. Denormalize only when a performance measurement proves it necessary.
  • UUID v7 for primary keys (time-sortable, no collisions in distributed systems).
  • Every table has: id (UUID PK), created_at (TIMESTAMPTZ), updated_at (TIMESTAMPTZ).
  • Soft deletes: use deleted_at TIMESTAMPTZ or is_active boolean.
CREATE TABLE orders (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  customer_id UUID NOT NULL REFERENCES customers(id),
  status order_status NOT NULL DEFAULT 'pending',
  total_amount NUMERIC(10,2) NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  deleted_at TIMESTAMPTZ  -- soft delete
);

CREATE INDEX idx_orders_customer_id ON orders(customer_id);
CREATE INDEX idx_orders_status ON orders(status) WHERE deleted_at IS NULL;

Step 2: Indexing Strategy

Index Type When Example
B-tree Equality and range lookups WHERE status = 'active'
Composite B-tree Multi-column filters WHERE status = 'active' AND created_at > '2026-01-01'
Partial Filtered subset WHERE status = 'active' on 10M rows, 90% inactive
Covering All columns in query covered Include selected columns to avoid heap lookups
GIN JSON, arrays, full-text WHERE tags @> ['urgent']
Unique Uniqueness enforcement WHERE email IS NOT NULL
BRIN Large, naturally-ordered data Time-series data, logs
Hash Equality only, large values URL lookup (smaller than B-tree)

Step 3: N+1 Detection and Fix

// N+1 — BAD
const users = await db.user.findMany();  // 1 query
for (const user of users) {
  const posts = await db.post.findMany({ where: { userId: user.id } });  // N queries
}

// Fixed — eager loading
const users = await db.user.findMany({ include: { posts: true } });  // 1 query
Full SKILL.md on GitHub

Allowed tools

Tools this skill is permitted to call.

No restriction — this skill can use any tool.

Bundled files

  • references/connection-pooling.md
  • references/database-fundamentals.md
  • references/database-migration-patterns.md
  • references/database-sharding.md
  • references/database-testing.md
  • references/migration-guide.md
  • references/migration-strategies.md
  • references/query-optimization.md
  • references/table-design-rules.md

FAQ

What does the backend-database-patterns skill do?

Use when the user asks about database schema design, slow queries, indexes, EXPLAIN ANALYZE, N+1 problems, transactions, keyset pagination, connection pooling or repository pattern. Produces schema, index and query fixes. Not for engine internals (use architecture-postgresql-internals) or migrations tooling (use database-migration).

How do I install the backend-database-patterns skill?

Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.

Does the backend-database-patterns skill run scripts?

No, this skill is instructions only (SKILL.md) with no executable scripts.

Related skills

Compare backend-database-patterns with