Agent skill

Database Patterns

by MadAppGang in MadAppGang/claude-code

A skill your agent uses when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL…

MITAuto-check passedDatabases

Install Database Patterns

skills CLI
$ npx skills add MadAppGang/claude-code --skill database-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install MadAppGang/claude-code database-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/MadAppGang/claude-code.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/dev/skills/backend/database-patterns .claude/skills/database-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
database-patterns
GitHub stars
284
Token cost
~2.2k tokens
SKILL.md length
196 words
Files
1
Skills in repo
69
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL…

  • Designing database schemas
  • SKILL.md covers Overview, Schema Design, Indexing Strategies and Query Patterns, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Implementing repository patterns

What it does

Database Patterns is an agent skill from MadAppGang/claude-code. Use when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL databases.

Its SKILL.md is about 2.2k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Databases, covering NoSQL databases, Database schema design and Design patterns. It works with SQL. The repository describes itself as: claude code plugins marketplace. The licence is MIT.

When your agent uses it

  • Designing database schemas
  • Implementing repository patterns
  • Writing optimized queries
  • Managing migrations

Example prompts

  • “/database-patterns”

What it can do on your machine

Read from SKILL.md and the folder at commit 6097ad4. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are sql, typescript and javascript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Database Patterns loads about 2.2k tokens when it runs. Until then it costs about 51 tokens; SKILL.md has 196 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~51
When it runs · the whole SKILL.md, loaded when a task matches
~2.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from MadAppGang/claude-code at commit 6097ad4, republished under its MIT licence (© MadAppGang). 196 words, ~2,233 tokens.

Download SKILL.mdSave it as .claude/skills/database-patterns/SKILL.md (or your agent's skills folder).
name
database-patterns
description
Use when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL databases.
version
1.0.0
keywords
database design, schema design, repository pattern, SQL queries, PostgreSQL, MySQL, MongoDB, indexes, migrations, transactions
plugin
dev
updated
2026-01-20

Database Patterns

Overview

Database design and access patterns for relational and NoSQL databases.

Schema Design

Normalization Levels
LevelDescriptionUse Case
1NFAtomic values, no repeating groupsBase requirement
2NFNo partial dependenciesMost applications
3NFNo transitive dependenciesOLTP systems
DenormalizedRedundant data for readsRead-heavy, analytics
Common Table Patterns
sql
-- Users table
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    status VARCHAR(20) DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Soft delete pattern
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL;
CREATE INDEX idx_users_deleted ON users(deleted_at) WHERE deleted_at IS NULL;

-- Audit columns
ALTER TABLE users ADD COLUMN created_by UUID REFERENCES users(id);
ALTER TABLE users ADD COLUMN updated_by UUID REFERENCES users(id);
Relationships
sql
-- One-to-Many
CREATE TABLE orders (
    id UUID PRIMARY KEY,
    user_id UUID NOT NULL REFERENCES users(id),
    total DECIMAL(10,2) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_orders_user ON orders(user_id);

-- Many-to-Many
CREATE TABLE order_products (
    order_id UUID REFERENCES orders(id) ON DELETE CASCADE,
    product_id UUID REFERENCES products(id) ON DELETE CASCADE,
    quantity INT NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    PRIMARY KEY (order_id, product_id)
);

-- Self-referential (tree/hierarchy)
CREATE TABLE categories (
    id UUID PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    parent_id UUID REFERENCES categories(id)
);
CREATE INDEX idx_categories_parent ON categories(parent_id);

Indexing Strategies

Index Types
TypeUse CaseExample
B-treeRange, equalityMost columns
HashEquality onlyExact matches
GINArrays, JSON, full-textJSONB, text search
GiSTGeometric, range typesPostGIS, IP ranges
Index Guidelines
sql
-- Primary key (automatic)
CREATE TABLE users (id UUID PRIMARY KEY);

-- Foreign keys
CREATE INDEX idx_orders_user ON orders(user_id);

-- Frequent filters
CREATE INDEX idx_users_status ON users(status);

-- Composite for multi-column queries
CREATE INDEX idx_orders_user_status ON orders(user_id, status);

-- Partial index for common queries
CREATE INDEX idx_active_users ON users(email) WHERE status = 'active';

-- Expression index
CREATE INDEX idx_users_email_lower ON users(LOWER(email));
When NOT to Index
  • Small tables (< 1000 rows)
  • Frequently updated columns
  • Low cardinality columns
  • Columns rarely used in WHERE

Query Patterns

Efficient Queries
sql
-- Use specific columns, not *
SELECT id, name, email FROM users WHERE id = $1;

-- Limit results
SELECT * FROM users ORDER BY created_at DESC LIMIT 20;

-- Exists vs COUNT
SELECT EXISTS(SELECT 1 FROM users WHERE email = $1);

-- Batch inserts
INSERT INTO users (name, email) VALUES
    ('User 1', 'user1@example.com'),
    ('User 2', 'user2@example.com'),
    ('User 3', 'user3@example.com');
Pagination
sql
-- Offset pagination (simple but slow for large offsets)
SELECT * FROM users ORDER BY created_at DESC LIMIT 20 OFFSET 100;

-- Cursor pagination (better performance)
SELECT * FROM users
WHERE created_at < $cursor
ORDER BY created_at DESC
LIMIT 20;

-- Keyset pagination with tie-breaker
SELECT * FROM users
WHERE (created_at, id) < ($cursor_time, $cursor_id)
ORDER BY created_at DESC, id DESC
LIMIT 20;
Common Query Patterns
sql
-- Upsert (INSERT or UPDATE)
INSERT INTO users (email, name)
VALUES ($1, $2)
ON CONFLICT (email)
DO UPDATE SET name = EXCLUDED.name, updated_at = NOW();

-- Soft delete
UPDATE users SET deleted_at = NOW() WHERE id = $1;
SELECT * FROM users WHERE deleted_at IS NULL;

-- Lock for update (prevent race conditions)
SELECT * FROM accounts WHERE id = $1 FOR UPDATE;

-- Bulk update
UPDATE orders SET status = 'shipped'
WHERE id = ANY($1::uuid[]);

Repository Pattern

Interface
typescript
interface UserRepository {
  findById(id: string): Promise<User | null>;
  findByEmail(email: string): Promise<User | null>;
  findAll(filter: UserFilter, pagination: Pagination): Promise<PaginatedResult<User>>;
  create(data: CreateUserInput): Promise<User>;
  update(id: string, data: UpdateUserInput): Promise<User>;
  delete(id: string): Promise<void>;
}
Implementation
typescript
class PostgresUserRepository implements UserRepository {
  constructor(private db: Database) {}

  async findById(id: string): Promise<User | null> {
    const result = await this.db.query(
      'SELECT * FROM users WHERE id = $1 AND deleted_at IS NULL',
      [id]
    );
    return result.rows[0] || null;
  }

  async create(data: CreateUserInput): Promise<User> {
    const result = await this.db.query(
      `INSERT INTO users (name, email, password_hash)
       VALUES ($1, $2, $3)
       RETURNING *`,
      [data.name, data.email, await hashPassword(data.password)]
    );
    return result.rows[0];
  }
}

Transaction Patterns

Basic Transaction
typescript
async function transferFunds(fromId: string, toId: string, amount: number) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // Lock accounts
    await client.query(
      'SELECT * FROM accounts WHERE id IN ($1, $2) FOR UPDATE',
      [fromId, toId]
    );

    // Debit
    await client.query(
      'UPDATE accounts SET balance = balance - $1 WHERE id = $2',
      [amount, fromId]
    );

    // Credit
    await client.query(
      'UPDATE accounts SET balance = balance + $1 WHERE id = $2',
      [amount, toId]
    );

    await client.query('COMMIT');
  } catch (e) {
    await client.query('ROLLBACK');
    throw e;
  } finally {
    client.release();
  }
}
Isolation Levels
LevelDirty ReadNon-Repeatable ReadPhantom Read
Read UncommittedYesYesYes
Read CommittedNoYesYes
Repeatable ReadNoNoYes
SerializableNoNoNo
sql
-- Set isolation level
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Migration Patterns

Migration Structure
migrations/
├── 001_create_users.sql
├── 002_add_user_status.sql
├── 003_create_orders.sql
└── 004_add_order_index.sql
Migration Best Practices
sql
-- Always reversible
-- UP
ALTER TABLE users ADD COLUMN phone VARCHAR(20);

-- DOWN
ALTER TABLE users DROP COLUMN phone;

-- Non-blocking index creation
CREATE INDEX CONCURRENTLY idx_users_phone ON users(phone);

-- Safe column renames (PostgreSQL)
ALTER TABLE users RENAME COLUMN name TO full_name;

-- Add NOT NULL safely
ALTER TABLE users ADD COLUMN status VARCHAR(20) DEFAULT 'active';
UPDATE users SET status = 'active' WHERE status IS NULL;
ALTER TABLE users ALTER COLUMN status SET NOT NULL;

Connection Pooling

Pool Configuration
typescript
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,              // Max connections
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});
Best Practices
  • Use connection pool (don't create new connections)
  • Release connections promptly
  • Set appropriate pool size (CPU cores * 2-4)
  • Handle connection errors gracefully

NoSQL Patterns (MongoDB/DynamoDB)

Document Design
javascript
// Embedded (for one-to-few)
{
  _id: ObjectId("..."),
  name: "John",
  addresses: [
    { type: "home", street: "123 Main St" },
    { type: "work", street: "456 Office Blvd" }
  ]
}

// Referenced (for one-to-many)
{
  _id: ObjectId("..."),
  name: "John",
  orderIds: [ObjectId("..."), ObjectId("...")]
}
DynamoDB Single-Table Design
PK              | SK                | Attributes
----------------|-------------------|------------------
USER#123        | METADATA          | name, email, ...
USER#123        | ORDER#001         | total, status, ...
USER#123        | ORDER#002         | total, status, ...
ORDER#001       | METADATA          | userId, total, ...
ORDER#001       | ITEM#1            | productId, qty, ...

Database design and access patterns

© MadAppGang, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in plugins/dev/skills/backend/database-patterns of MadAppGang/claude-code.

Open the folder on GitHubat commit 6097ad4

Compare with similar skills

Database Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Database Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Database Patterns this skillMadAppGang/claude-code284—~2.2kAutomated safety check: PassMIT
Database Architecture InterviewerPrepLabsAI/InterviewMentor112—~2.4kAutomated safety check: PassMIT
Database MigrationDokhacgiakhoa/Agent-Skills-4-Vibe-Coding-CLI507—~227Automated safety check: PassCustom licence
Database Patternsyonatangross/orchestkit289—~2.5kAutomated safety check: PassMIT
Databaseaiskillstore/marketplace4303 repos~1.2kAutomated safety check: PassNone
Database FundamentalsDanielPodolsky/ownyourcode2901 repos~1.6kAutomated safety check: PassMIT

Similar skills

  • Database Architecture Interviewer

    PrepLabsAI/InterviewMentor

    A Principal Database Engineer interviewer. An agent skill from PrepLabsAI/InterviewMentor.

    112 GitHub stars~2.4k tokensUpdated yesterday
    DatabasesAuto-check passed
  • Database Migration

    Dokhacgiakhoa/Agent-Skills-4-Vibe-Coding-CLI

    MASTER DB: Zero-Downtime, Schema Design (3NF), SQL/NoSQL. An agent skill from Dokhacgiakhoa/Agent-Skills-4-Vibe-Coding-CLI.

    507 GitHub stars~227 tokensUpdated 3 mo ago
    DatabasesAuto-check passed
  • Database Patterns

    yonatangross/orchestkit

    Database design and migration patterns for Alembic migrations, schema design (SQL/NoSQL), and database versioning.

    289 GitHub stars~2.5k tokensUpdated today
    DatabasesAuto-check passed
  • Database

    aiskillstore/marketplace

    Database development and operations workflow covering SQL, NoSQL, database design, migrations, optimization, and data engineering.

    430 GitHub starsUsed in 3 repos~1.2k tokens
    DatabasesAuto-check passed
  • Database Fundamentals

    DanielPodolsky/ownyourcode

    Reviews schema design, SQL queries, ORM patterns. An agent skill from DanielPodolsky/ownyourcode.

    290 GitHub starsUsed in 1 repo~1.6k tokens
    DatabasesAuto-check passed
  • Mongodb Schema Design

    mongodb/agent-skills

    Official

    MongoDB schema design patterns and anti-patterns. An agent skill from mongodb/agent-skills.

    190 GitHub starsUsed in 2 repos~3.4k tokens
    DatabasesAuto-check passed

More from MadAppGang/claude-code

All 69 skills in this repo
  • API Spec Analyzer

    MadAppGang/claude-code

    Analyzes API documentation from OpenAPI specs to provide TypeScript interfaces, request/response formats, and implementation guidance.

    284 GitHub starsUsed in 1 repo~2.7k tokens
    Auto-check passed
  • Content Brief

    MadAppGang/claude-code

    Content brief template and creation methodology for SEO-optimized content.

    284 GitHub starsUsed in 1 repo~959 tokens
    Auto-check passed
  • Context Detection

    MadAppGang/claude-code

    A skill your agent uses when detecting project technology stack from files/configs/directory structure, auto-loading framework-specific skills, or analyzing multi-stack fullstack projects (e.g…

    284 GitHub stars~5.4k tokensUpdated 6 mo ago
    Auto-check passed
  • Content Optimizer

    MadAppGang/claude-code

    On-page SEO optimization techniques including keyword density, meta tags, heading structure, and readability.

    284 GitHub starsUsed in 1 repo~694 tokens
    Auto-check passed
  • Keyword Cluster Builder

    MadAppGang/claude-code

    Techniques for expanding seed keywords and clustering by topic and intent.

    284 GitHub starsUsed in 1 repo~674 tokens
    Auto-check passed
  • Serp Analysis

    MadAppGang/claude-code

    SERP analysis techniques for intent classification, feature identification, and competitive intelligence.

    284 GitHub starsUsed in 1 repo~1k tokens
    Auto-check passed

Works with

Categories

Questions about Database Patterns

What does Database Patterns do?

A skill your agent uses when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL…. Database Patterns is an agent skill from MadAppGang/claude-code. Use when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL databases.

When should I use Database Patterns?

Database Patterns fits situations like: designing database schemas; implementing repository patterns; writing optimized queries; managing migrations.

How do I install Database Patterns in Claude Code?

Run `npx skills add MadAppGang/claude-code --skill database-patterns -a claude-code`. Or copy the skill folder (plugins/dev/skills/backend/database-patterns in MadAppGang/claude-code) into .claude/skills/database-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Database Patterns in Codex?

Run `npx skills add MadAppGang/claude-code --skill database-patterns -a codex`. Or copy the skill folder (plugins/dev/skills/backend/database-patterns in MadAppGang/claude-code) into .agents/skills/database-patterns in your project. Codex loads it when a task matches its description.

Can I use Database Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add MadAppGang/claude-code --skill database-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/database-patterns, .gemini/skills/database-patterns, .github/skills/database-patterns and .opencode/skills/database-patterns in your project.

What does Database Patterns need to run?

SKILL.md names no scripts, command-line tools or credentials: Database Patterns is instructions for the agent only.

Does Database Patterns access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Database Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Database Patterns use?

Database Patterns is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Database Patterns use?

About 2.2k tokens (SKILL.md is roughly 8.9k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Database Patterns?

Skills that share tags, products or a category with Database Patterns: Database Architecture Interviewer (PrepLabsAI/InterviewMentor, 112 stars), Database Migration (Dokhacgiakhoa/Agent-Skills-4-Vibe-Coding-CLI, 507 stars), Database Patterns (yonatangross/orchestkit, 289 stars) and Database (aiskillstore/marketplace, 430 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Database Patterns?

MadAppGang (a GitHub organization) maintains it in MadAppGang/claude-code, which has 284 GitHub stars. The repository holds 69 skills in this directory. The repository was last updated on March 15, 2026.

Source: MadAppGang/claude-code on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.