Agent skill

Database Patterns

by softspark in softspark/ai-toolkit

DB schema design and query tuning: normalization, indexing, N+1, transactions, EXPLAIN.

Apache-2.0Auto-check passedDatabases

Install Database Patterns

skills CLI
$ npx skills add softspark/ai-toolkit --skill database-patterns -a claude-code

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

GitHub CLI
$ gh skill install softspark/ai-toolkit 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/softspark/ai-toolkit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/app/skills/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
179
Token cost
~2.5k tokens
SKILL.md length
708 words
Files
1
Skills in repo
112
Repo updated
First seen
Licence
Apache-2.0

At a glance

DB schema design and query tuning: normalization, indexing, N+1, transactions, EXPLAIN.

  • Tasks that involve Query optimization
  • SKILL.md covers ORM Selection, Schema Design, Index Strategies and Query Optimization, plus 6 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Tasks that involve Database schema design

What it does

Database Patterns is an agent skill from softspark/ai-toolkit. DB schema design and query tuning: normalization, indexing, N+1, transactions, EXPLAIN. Triggers: schema, index, slow query, N+1, PostgreSQL, MySQL, EXPLAIN, deadlock, query plan.

Its SKILL.md is about 2.5k 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 Query optimization, Database schema design and ORMs and data access. It works with MySQL and PostgreSQL. The repository describes itself as: Professional-grade AI coding toolkit: 94 skills, 44 agents, multi-platform (Claude, Cursor, Windsurf, Copilot, Gemini, Cline, Roo Code, Aider, Augment, Antigravity, Codex CLI… The licence is Apache-2.0.

When your agent uses it

  • Tasks that involve Query optimization
  • Tasks that involve Database schema design
  • Tasks that involve ORMs and data access

Example prompts

  • “/database-patterns”

Requirements

  • Python 3
  • Node.js
  • Pre-approved tools (allowed-tools): Read

What it can do on your machine

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

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read

    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, python and ini).

    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.5k tokens when it runs. Until then it costs about 49 tokens; SKILL.md has 708 words of instructions outside code blocks.

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

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 softspark/ai-toolkit at commit d64db2b, republished under its Apache-2.0 licence (© softspark). 708 words, ~2,486 tokens.

Download SKILL.mdSave it as .claude/skills/database-patterns/SKILL.md (or your agent's skills folder).
name
database-patterns
description
DB schema design and query tuning: normalization, indexing, N+1, transactions, EXPLAIN. Triggers: schema, index, slow query, N+1, PostgreSQL, MySQL, EXPLAIN, deadlock, query plan.
allowed-tools
Read
effort
medium
user-invocable
false

Database Patterns Skill

ORM Selection

ScenarioORM
Node.js, type-safePrisma
Node.js, SQL-firstDrizzle
Python, asyncSQLAlchemy 2.0
Python, simpleSQLModel
PHPDoctrine, Eloquent

Schema Design

Naming Conventions
sql
-- Tables: plural, snake_case
CREATE TABLE user_profiles (...);

-- Columns: snake_case
user_id, created_at, is_active

-- Indexes: idx_{table}_{columns}
CREATE INDEX idx_users_email ON users(email);

-- Foreign keys: fk_{table}_{ref_table}
CONSTRAINT fk_orders_users FOREIGN KEY (user_id) REFERENCES users(id)
Common Patterns
Soft Delete
sql
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL;

-- Query active records
SELECT * FROM users WHERE deleted_at IS NULL;
Audit Columns
sql
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created_by UUID REFERENCES users(id),
updated_by UUID REFERENCES users(id)
UUID vs Serial
Use CaseType
Internal onlySERIAL/BIGSERIAL
External/distributedUUID
Human readableSERIAL with prefix

Index Strategies

When to Index
  • Foreign keys (always)
  • Columns in WHERE clauses
  • Columns in ORDER BY
  • Columns in JOIN conditions
Index Types
TypeUse Case
B-treeEquality, range (default)
HashEquality only
GINArrays, JSONB, full-text
GiSTGeometric, full-text
BRINLarge sequential data
Composite Index Order
sql
-- Good: matches query pattern
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
SELECT * FROM orders WHERE user_id = 1 AND created_at > '2024-01-01';

-- Index used for:
-- WHERE user_id = 1
-- WHERE user_id = 1 AND created_at > ...

-- Index NOT used for:
-- WHERE created_at > '2024-01-01' (missing leading column)

Query Optimization

Explain Analyze
sql
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = 'test@example.com';
Common Issues
IssueSolution
Seq Scan on large tableAdd index
High row estimateUpdate statistics
Nested Loop on large setsConsider hash join
Sort in memoryIncrease work_mem
N+1 Prevention
python
# Bad: N+1
for user in users:
    print(user.orders)  # Query per user

# Good: Eager loading
users = User.query.options(joinedload(User.orders)).all()

Migration Best Practices

Safe Migrations
sql
-- Add column (safe)
ALTER TABLE users ADD COLUMN phone VARCHAR(20);

-- Add NOT NULL column (safe pattern)
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
UPDATE users SET phone = '' WHERE phone IS NULL;
ALTER TABLE users ALTER COLUMN phone SET NOT NULL;

-- Rename column (use application-level)
-- 1. Add new column
-- 2. Copy data
-- 3. Update application
-- 4. Remove old column
Migration Checklist
  • Tested on production-like data
  • Rollback script ready
  • No long locks on large tables
  • Indexes created concurrently
  • Application handles both states

Connection Pooling

PgBouncer Settings
ini
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
Application Settings
FrameworkPool Size Formula
General(cores * 2) + disk spindles
Read-heavycores * 4
Write-heavycores * 2

Vector Database (Qdrant) Patterns

Client Setup
python
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct

# Sync client
client = QdrantClient(host="localhost", port=6333)

# Async client
from qdrant_client import AsyncQdrantClient
async_client = AsyncQdrantClient(host="localhost", port=6333)
Collection Management
python
# Create collection (single vector)
client.create_collection(
    collection_name="documents",
    vectors_config=VectorParams(size=384, distance=Distance.COSINE)
)

# Create collection (multi-vector)
from qdrant_client.models import VectorParams

client.create_collection(
    collection_name="multimodal",
    vectors_config={
        "text": VectorParams(size=384, distance=Distance.COSINE),
        "image": VectorParams(size=512, distance=Distance.EUCLID),
    }
)
Upserting Vectors
python
# Single upsert
client.upsert(
    collection_name="documents",
    points=[
        PointStruct(
            id=1,
            vector=[0.1, 0.2, 0.3, ...],  # 384-dim vector
            payload={"title": "Doc 1", "category": "tech"}
        )
    ]
)

# Batch upsert
points = [
    PointStruct(id=i, vector=vectors[i], payload=payloads[i])
    for i in range(len(vectors))
]
client.upsert(collection_name="documents", points=points, batch_size=100)
Searching Vectors
python
from qdrant_client.models import Filter, FieldCondition, MatchValue

# Basic search
results = client.search(
    collection_name="documents",
    query_vector=[0.1, 0.2, ...],
    limit=10
)

# Search with filter
results = client.search(
    collection_name="documents",
    query_vector=[0.1, 0.2, ...],
    query_filter=Filter(
        must=[
            FieldCondition(key="category", match=MatchValue(value="tech"))
        ]
    ),
    limit=10,
    with_payload=True,
    score_threshold=0.7
)

# Search with range filter
from qdrant_client.models import Range

results = client.search(
    collection_name="documents",
    query_vector=query_vector,
    query_filter=Filter(
        must=[
            FieldCondition(key="price", range=Range(gte=10, lte=100))
        ]
    ),
    limit=10
)
Payload Indexing
python
# Create payload index for faster filtering
client.create_payload_index(
    collection_name="documents",
    field_name="category",
    field_schema="keyword"  # or "integer", "float", "bool"
)
Best Practices
AspectRecommendation
Batch Size100-1000 points per upsert
Vector DimMatch your embedding model (384, 768, 1536)
FiltersIndex frequently filtered fields
DistanceCOSINE for normalized, EUCLID for raw
ShardingUse for >1M vectors
Distance Metrics
MetricBest ForNormalized
COSINEText embeddingsYes
EUCLIDImage embeddingsNo
DOTWhen vectors pre-normalizedYes

Common Rationalizations

ExcuseWhy It's Wrong
"We'll add indexes later when it's slow"Missing indexes on production tables cause outages, not slowdowns — index from design
"The ORM handles performance"ORMs generate queries, they don't optimize them — always check the query plan
"NoSQL is faster"NoSQL trades consistency for speed — if you need joins, use a relational DB
"We don't need migrations, we'll update the schema directly"Direct schema changes are irreversible and untestable — migrations are the safety net
"One big table is simpler"Denormalization without measurement creates update anomalies — normalize first, denormalize with data

Rules

  • MUST profile queries with EXPLAIN (ANALYZE, BUFFERS) before adding an index — indexes chosen by intuition miss the real hot path half the time
  • MUST design the schema around the dominant access pattern, not the logical entity graph — storage follows queries, not the other way round
  • NEVER write to production with raw SQL when a migration file fits — ad-hoc changes break rollback and audit
  • NEVER add a SELECT * in a loop — N+1 is the most common performance regression in code review
  • CRITICAL: every foreign key has an index on the referencing column. Postgres does not create one automatically, and ON DELETE CASCADE without the index causes full-table scans on delete.
  • MANDATORY: numeric IDs use bigint (or bigserial) in new tables unless there is a stated reason to cap at 2^31. Integer overflow on a growing table is a late, painful surprise.
Show full SKILL.md (226 more words)Show less

Gotchas

  • EXPLAIN without ANALYZE shows the planner's estimate, not the actual execution. A query plan that "looks good" with EXPLAIN can still be slow in practice — always use ANALYZE for real diagnosis.
  • ORM-generated queries often look efficient in one row but emit N+1 at scale. prisma, sequelize, activerecord all have "eager loading" switches that must be explicit — the default is lazy and bites under load.
  • Postgres transactions hold row locks until commit or rollback. A long-running transaction that reads rows another writer needs blocks progress silently. Investigate pg_stat_activity for state=idle in transaction when writes stall.
  • Index-only scans require both the query columns AND the filter to be in the index (or in the visibility map for heap tuples). Adding a single column to WHERE can demote an index-only scan to an index scan with a 10× slowdown.
  • MySQL implicit collation on JOIN across tables with different utf8mb4 collations forces a row-by-row collation conversion — a 100× slowdown that shows as a full scan in the plan. Align collations during schema design.

When NOT to Load

  • For schema evolution (zero-downtime, expand-contract, backfill) — use /migration-patterns
  • For running migrations as a task — use /migrate
  • For query-plan profiling and the four golden signals — use /performance-profiling
  • For vector/embedding-specific schema — this skill covers the mechanics; use /rag-patterns for retrieval design
  • For observability of DB metrics (slow query log, connection pool saturation) — use /observability-patterns

© softspark, Apache-2.0. 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 app/skills/database-patterns of softspark/ai-toolkit.

Open the folder on GitHubat commit d64db2b

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 skillsoftspark/ai-toolkit179—~2.5kAutomated safety check: PassApache-2.0
SQL ToolkitLeoYeAI/openclaw-master-skills2.2k—~3kAutomated safety check: PassMIT
Database Expertcin12211/orca-q223—~2.8kAutomated safety check: PassMIT
DB SculptorEliasOulkadi/shokunin114—~3.1kAutomated safety check: NotesMIT
SQL ProJeffallan/claude-skills12k—~1.3kAutomated safety check: PassMIT
Discover Databaserand/cc-polymath181—~2kAutomated safety check: PassMIT

Similar skills

  • SQL Toolkit

    LeoYeAI/openclaw-master-skills

    Query, design, migrate, and optimize SQL databases. An agent skill from LeoYeAI/openclaw-master-skills.

    2.2k GitHub stars~3k tokensUpdated 2 mo ago
    DatabasesAuto-check passed
  • Database Expert

    cin12211/orca-q

    Database performance optimization, schema design, query analysis, and connection management across PostgreSQL, MySQL, MongoDB, and SQLite with ORM integration.

    223 GitHub stars~2.8k tokensUpdated 16 days ago
    DatabasesAuto-check passed
  • DB Sculptor

    EliasOulkadi/shokunin

    Design database schemas with Prisma/Drizzle, PostgreSQL index strategy (B-tree, GIN, GiST, BRIN, Hash), query optimization (EXPLAIN ANALYZE), migration safety (expand/contract, zero-downtime), and…

    114 GitHub stars~3.1k tokensUpdated 2 days ago
    DatabasesAuto-check: notes
  • SQL Pro

    Jeffallan/claude-skills

    Optimizes SQL queries and designs schemas using CTEs, window functions, covering indexes and EXPLAIN ANALYZE, with notes on dialect differences between major databases.

    12k GitHub stars~1.3k tokensUpdated 4 days ago
    DatabasesAuto-check passed
  • Discover Database

    rand/cc-polymath

    Automatically discover database skills when working with SQL, PostgreSQL, MongoDB, Redis, database schema design, query optimization, migrations, connection pooling, ORMs, or database selection.

    181 GitHub stars~2k tokensUpdated 7 mo ago
    DatabasesAuto-check passed
  • Rules and examples for safe, reversible schema changes in production: zero-downtime column and index changes, large data backfills and ORM migration workflows.

    274k GitHub stars~3.3k tokensUpdated 2 days ago
    DatabasesAuto-check passed

More from softspark/ai-toolkit

All 112 skills in this repo
  • Prepare Test Env

    softspark/ai-toolkit

    Prepare or verify a project QA environment with source identity, readiness, browser access, evidence paths and owned cleanup.

    179 GitHub stars~1.8k tokensUpdated today
    Auto-check: notes
  • A11y Validate

    softspark/ai-toolkit

    Accessibility validator: WCAG 2.1 AA, EN 301 549, EAA. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~3.8k tokensUpdated today
    Auto-check: notes
  • Analyze

    softspark/ai-toolkit

    Analyzes code quality, complexity, patterns across codebase.

    179 GitHub stars~1k tokensUpdated today
    Auto-check passed
  • Autonomous Dev

    softspark/ai-toolkit

    Drives a brief, specification, issue or existing PR through implementation, review, tests and QA to a ready PR.

    179 GitHub stars~2.6k tokensUpdated today
    Auto-check: notes
  • Brand Voice

    softspark/ai-toolkit

    Direct technical voice for docs, README, user-facing text. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~2.1k tokensUpdated today
    Auto-check passed
  • CI

    softspark/ai-toolkit

    Detect/generate/debug CI pipeline config (GitHub Actions, GitLab CI).

    179 GitHub stars~1.1k tokensUpdated today
    Auto-check: notes

Works with

Categories

Questions about Database Patterns

What does Database Patterns do?

DB schema design and query tuning: normalization, indexing, N+1, transactions, EXPLAIN. Database Patterns is an agent skill from softspark/ai-toolkit. DB schema design and query tuning: normalization, indexing, N+1, transactions, EXPLAIN.

When should I use Database Patterns?

Database Patterns fits situations like: tasks that involve Query optimization; tasks that involve Database schema design; tasks that involve ORMs and data access.

How do I install Database Patterns in Claude Code?

Run `npx skills add softspark/ai-toolkit --skill database-patterns -a claude-code`. Or copy the skill folder (app/skills/database-patterns in softspark/ai-toolkit) 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 softspark/ai-toolkit --skill database-patterns -a codex`. Or copy the skill folder (app/skills/database-patterns in softspark/ai-toolkit) 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 softspark/ai-toolkit --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. Our summary lists: Python 3; Node.js. Its frontmatter pre-approves these tools: Read.

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 Apache-2.0 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.5k tokens (SKILL.md is roughly 9.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: SQL Toolkit (LeoYeAI/openclaw-master-skills, 2.2k stars), Database Expert (cin12211/orca-q, 223 stars), DB Sculptor (EliasOulkadi/shokunin, 114 stars) and SQL Pro (Jeffallan/claude-skills, 12k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Database Patterns?

softspark (a GitHub user) maintains it in softspark/ai-toolkit, which has 179 GitHub stars. The repository holds 112 skills in this directory. The repository was last updated on October 7, 2026.

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