SQL Optimization Patterns
ynulihao/AgentSkillOS
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries.
Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases.
$ npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install CloudAI-X/claude-workflow-v2 database-design --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/CloudAI-X/claude-workflow-v2.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/database-design .claude/skills/database-design && rm -rf skills-srcUse ~/.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/
Install the "database-design" agent skill from https://github.com/CloudAI-X/claude-workflow-v2/tree/main/skills/database-design into .claude/skills/database-design/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "database-design", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/CloudAI-X/claude-workflow-v2/tree/main/skills/database-designType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install CloudAI-X/claude-workflow-v2 database-design --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/CloudAI-X/claude-workflow-v2.git skills-src && mkdir -p .agents/skills && cp -r skills-src/skills/database-design .agents/skills/database-design && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "database-design" agent skill from https://github.com/CloudAI-X/claude-workflow-v2/tree/main/skills/database-design into .agents/skills/database-design/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "database-design", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install CloudAI-X/claude-workflow-v2 database-design --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/CloudAI-X/claude-workflow-v2.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/skills/database-design .cursor/skills/database-design && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "database-design" agent skill from https://github.com/CloudAI-X/claude-workflow-v2/tree/main/skills/database-design into .cursor/skills/database-design/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "database-design", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/CloudAI-X/claude-workflow-v2.git --path skills/database-design--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install CloudAI-X/claude-workflow-v2 database-design --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/CloudAI-X/claude-workflow-v2.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/skills/database-design .gemini/skills/database-design && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "database-design" agent skill from https://github.com/CloudAI-X/claude-workflow-v2/tree/main/skills/database-design into .gemini/skills/database-design/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "database-design", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install CloudAI-X/claude-workflow-v2 database-designInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/CloudAI-X/claude-workflow-v2.git skills-src && mkdir -p .github/skills && cp -r skills-src/skills/database-design .github/skills/database-design && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "database-design" agent skill from https://github.com/CloudAI-X/claude-workflow-v2/tree/main/skills/database-design into .github/skills/database-design/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "database-design", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install CloudAI-X/claude-workflow-v2 database-design --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/CloudAI-X/claude-workflow-v2.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/skills/database-design .opencode/skills/database-design && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "database-design" agent skill from https://github.com/CloudAI-X/claude-workflow-v2/tree/main/skills/database-design into .opencode/skills/database-design/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "database-design", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
database-designDesigns database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases.
Database Design is an agent skill from CloudAI-X/claude-workflow-v2. Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases. Use when designing tables, optimizing queries, fixing N+1 problems, planning migrations, or when asked about database performance, normalization, ORMs, or data modeling.
Its SKILL.md is about 2.8k 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 Database schema design. It works with SQL. The repository describes itself as: Universal Claude Code workflow plugin with agents, skills, hooks, and commands. The licence is MIT.
Read from SKILL.md and the folder at commit 3b5a89e. It shows what the files ask for, not the result of running them.
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.
No scripts in the folder and no shell commands in SKILL.md (its code samples are sql, javascript and python).
From the folder's file list and the shell code blocks in SKILL.md.
No URLs in SKILL.md.
From URLs in SKILL.md, links to its own repository left out.
Names no API keys, tokens, secrets or passwords.
From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Database Design loads about 2.8k tokens when it runs. Until then it costs about 76 tokens; SKILL.md has 114 words of instructions outside code blocks.
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.
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.
The full file from CloudAI-X/claude-workflow-v2 at commit 3b5a89e, republished under its MIT licence (© CloudAI-X). 114 words, ~2,755 tokens.
.claude/skills/database-design/SKILL.md (or your agent's skills folder).Copy this checklist and track progress:
Database Design Progress:
- [ ] Step 1: Identify entities and relationships
- [ ] Step 2: Normalize schema (3NF minimum)
- [ ] Step 3: Evaluate denormalization needs
- [ ] Step 4: Design indexes for query patterns
- [ ] Step 5: Write and optimize critical queries
- [ ] Step 6: Plan migration strategy
- [ ] Step 7: Configure connection pooling
- [ ] Step 8: Validate against anti-patterns checklist1NF: Atomic values, no repeating groups
2NF: 1NF + no partial dependencies (all non-key columns depend on full PK)
3NF: 2NF + no transitive dependencies (non-key columns don't depend on other non-key columns)-- WRONG: Unnormalized
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_name TEXT,
customer_email TEXT, -- duplicated across orders
product1_name TEXT, -- repeating groups
product1_qty INT,
product2_name TEXT,
product2_qty INT
);
-- CORRECT: Normalized to 3NF
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INT REFERENCES customers(id),
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE order_items (
id SERIAL PRIMARY KEY,
order_id INT REFERENCES orders(id),
product_id INT REFERENCES products(id),
quantity INT NOT NULL CHECK (quantity > 0)
);Denormalize only when you have measured proof of performance issues:
-- Acceptable denormalization: precomputed counter to avoid COUNT(*)
ALTER TABLE posts ADD COLUMN comment_count INT DEFAULT 0;
-- Update via trigger or application code
CREATE FUNCTION update_comment_count() RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id;
ELSIF TG_OP = 'DELETE' THEN
UPDATE posts SET comment_count = comment_count - 1 WHERE id = OLD.post_id;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER comments_count AFTER INSERT OR DELETE ON comments
FOR EACH ROW EXECUTE FUNCTION update_comment_count();B-tree (default): Equality, range, sorting, LIKE 'prefix%'
Hash: Equality only (rarely better than B-tree)
GIN: Full-text search, JSONB, arrays
GiST: Geometry, range types, full-text
BRIN: Large tables with naturally ordered data (timestamps)-- Column order matters: leftmost prefix rule
CREATE INDEX idx_users_status_created ON users (status, created_at);
-- This index supports:
-- WHERE status = 'active' -- YES
-- WHERE status = 'active' AND created_at > '2024' -- YES
-- WHERE created_at > '2024' -- NO (skips first column)-- Partial index: only index rows matching condition
CREATE INDEX idx_orders_pending ON orders (created_at)
WHERE status = 'pending'; -- smaller index, faster lookups
-- Covering index: include columns to avoid table lookup
CREATE INDEX idx_users_email_covering ON users (email)
INCLUDE (name, avatar_url); -- index-only scan for profile lookups-- WRONG: Index on low-cardinality column alone
CREATE INDEX idx_users_active ON users (is_active); -- boolean = 2 values
-- WRONG: Too many indexes (slows writes)
-- Every INSERT/UPDATE must update ALL indexes
-- CORRECT: Composite index targeting actual queries
CREATE INDEX idx_users_active_created ON users (is_active, created_at DESC)
WHERE is_active = true;EXPLAIN ANALYZE SELECT u.name, COUNT(o.id)
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE u.status = 'active'
GROUP BY u.name;
-- Key things to look for:
-- Seq Scan -> missing index (on large tables)
-- Nested Loop -> fine for small sets, bad for large joins
-- Hash Join -> good for large equi-joins
-- Sort -> consider index to avoid sort
-- actual time -> real execution time
-- rows -> if estimated vs actual differ wildly, run ANALYZE# WRONG: N+1 queries (1 query for users + N queries for orders)
users = db.query(User).all()
for user in users:
orders = db.query(Order).filter(Order.user_id == user.id).all() # N queries!
# CORRECT: Eager loading with SQLAlchemy
users = db.query(User).options(joinedload(User.orders)).all()
# CORRECT: Batch query
user_ids = [u.id for u in users]
orders = db.query(Order).filter(Order.user_id.in_(user_ids)).all()
orders_by_user = defaultdict(list)
for order in orders:
orders_by_user[order.user_id].append(order)// WRONG: N+1 with Prisma
const users = await prisma.user.findMany();
for (const user of users) {
const orders = await prisma.order.findMany({ where: { userId: user.id } }); // N+1!
}
// CORRECT: Include relation
const users = await prisma.user.findMany({
include: { orders: true },
});
// CORRECT: Batch with findMany + in
const userIds = users.map((u) => u.id);
const orders = await prisma.order.findMany({
where: { userId: { in: userIds } },
});-- WRONG: OFFSET pagination (rescans all skipped rows)
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 10000;
-- CORRECT: Cursor-based pagination (keyset)
SELECT * FROM posts
WHERE (created_at, id) < ('2024-01-15T10:30:00Z', 12345)
ORDER BY created_at DESC, id DESC
LIMIT 20;1. Never rename a column in one step (add new, migrate data, drop old)
2. Never drop a column that's still read by running code
3. Add columns as nullable or with defaults
4. Create indexes CONCURRENTLY to avoid locking
5. Test rollback before deploying-- Step 1: Add new column (brief ACCESS EXCLUSIVE lock — set lock_timeout and retry)
ALTER TABLE users ADD COLUMN display_name TEXT;
-- Step 2: Deploy code that writes to BOTH columns
-- Step 3: Backfill existing rows (do in batches)
UPDATE users SET display_name = name WHERE display_name IS NULL AND id BETWEEN 1 AND 10000;
-- Step 4: Deploy code that reads from new column
-- Step 5: Drop old column (after confirming no reads)
ALTER TABLE users DROP COLUMN name;-- WRONG: Blocks writes on the table
CREATE INDEX idx_orders_user ON orders (user_id);
-- CORRECT: Non-blocking (PostgreSQL)
CREATE INDEX CONCURRENTLY idx_orders_user ON orders (user_id);
-- Cannot run inside a transaction block: most migration tools wrap migrations
-- in one, so disable the transaction for this migrationRule of thumb: connections = (CPU cores * 2) + disk spindles
For most apps: 10-20 connections per application instance# SQLAlchemy connection pool
engine = create_engine(
DATABASE_URL,
pool_size=10, # maintained connections
max_overflow=20, # extra connections under load
pool_timeout=30, # seconds to wait for connection
pool_recycle=1800, # recycle connections every 30 min
pool_pre_ping=True, # verify connection before use
)// Prisma datasource
// In schema.prisma:
// datasource db {
// provider = "postgresql"
// url = env("DATABASE_URL")
// }
// Connection limit via URL: ?connection_limit=10&pool_timeout=30# WRONG: Fetches all columns
users = db.query(User).all()
# CORRECT: Select specific columns
users = db.query(User.id, User.name).all()// WRONG: Fetches everything
const users = await prisma.user.findMany();
// CORRECT: Select specific fields
const users = await prisma.user.findMany({
select: { id: true, name: true, email: true },
});# WRONG: Individual inserts in a loop
for item in items:
db.add(Item(**item))
db.commit() # commit per item!
# CORRECT: Bulk insert
db.bulk_insert_mappings(Item, items)
db.commit()// WRONG: Sequential creates
for (const item of items) {
await prisma.item.create({ data: item });
}
// CORRECT: Batch create
await prisma.item.createMany({ data: items });
// CORRECT: Transaction for dependent operations
await prisma.user.create({
data: { ...userData, profile: { create: profileData } },
});// Design for access patterns, not normalization
// Embed when: 1:1, 1:few, data read together
// Reference when: 1:many, many:many, data grows unbounded
// WRONG: Normalizing in MongoDB like SQL
// users collection: { _id, name }
// addresses collection: { _id, userId, street } // requires joins
// CORRECT: Embed bounded, co-accessed data
{
_id: ObjectId("..."),
name: "Alice",
addresses: [
{ street: "123 Main St", city: "NYC", type: "home" },
{ street: "456 Work Ave", city: "NYC", type: "work" }
]
}
// CORRECT: Reference unbounded or independent data
// user: { _id, name }
// orders: { _id, userId, items: [...], total: 99.99 } // index orders.userId# Cache-aside pattern
1. Check cache for key
2. If miss, query database
3. Store result in cache with TTL
4. Return result
# Cache invalidation
- TTL-based: SET key value EX 3600 (1 hour)
- Event-based: Delete key on write
- Write-through: Update cache on every writeAVOID DO INSTEAD
-------------------------------------------------------------------
SELECT * SELECT specific columns
OFFSET pagination Cursor-based pagination
N+1 queries Eager load or batch queries
Indexing every column Index based on query patterns
UUID v4 as primary key UUID v7 or BIGSERIAL (better locality)
Storing money as FLOAT Use DECIMAL / BIGINT (cents)
No foreign keys "for speed" Use foreign keys (data integrity)
Giant migrations Small, reversible steps
No connection pooling Always pool connections
Premature denormalization Normalize first, denormalize with data© CloudAI-X, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
Just SKILL.md in skills/database-design of CloudAI-X/claude-workflow-v2.
Open the folder on GitHubat commit 3b5a89e
Database Design 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.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Database Design this skillCloudAI-X/claude-workflow-v2 | 1.4k | — | ~2.8k | Automated safety check: Pass | MIT | |
| SQL Optimization Patternsynulihao/AgentSkillOS | 617 | 10 repos | ~3.3k | Automated safety check: Pass | None | |
| DB Migrationskurealnum/dotfiles | 290 | — | ~820 | Automated safety check: Pass | None | |
| SQL Prodavila7/claude-code-templates | 32k | 8 repos | ~1.9k | Automated safety check: Pass | MIT | |
| Optimizing Ef Core Queriesdotnet/skills | 5.6k | 1 repos | ~2.7k | Automated safety check: Pass | MIT | |
| Migrationkortix-ai/suna | 20k | — | ~1.2k | Automated safety check: Pass | Custom licence |
ynulihao/AgentSkillOS
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries.
kurealnum/dotfiles
A skill your agent uses when generating or regenerating Drizzle migration files, changing database schema tables or columns, resolving migration sequence conflicts after rebase, reviewing migration…
davila7/claude-code-templates
Master modern SQL with cloud-native databases, OLTP/OLAP optimization, and advanced query techniques.
dotnet/skills
Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster.
kortix-ai/suna
How to change the database schema in this repo. An agent skill from kortix-ai/suna.
first-fluke/oh-my-agent
Database specialist for SQL, NoSQL, and vector database modeling, schema design, normalization, indexing, transactions, integrity, concurrency control, backup, capacity planning, data standards…
CloudAI-X/claude-workflow-v2
Analyzes codebases to understand structure, tech stack, patterns, and conventions.
CloudAI-X/claude-workflow-v2
Designs REST and GraphQL APIs including endpoints, error handling, versioning, and documentation.
CloudAI-X/claude-workflow-v2
Designs software architecture and selects appropriate patterns for projects.
CloudAI-X/claude-workflow-v2
Designs and implements testing strategies for any codebase. An agent skill from CloudAI-X/claude-workflow-v2.
CloudAI-X/claude-workflow-v2
Manages Git workflows including branching, commits, and pull requests.
CloudAI-X/claude-workflow-v2
Analyzes and optimizes application performance across frontend, backend, and database layers.
Works with
Categories
Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases. Database Design is an agent skill from CloudAI-X/claude-workflow-v2. Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases.
Database Design fits situations like: designing tables; optimizing queries; fixing N+1 problems; planning migrations.
Run `npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a claude-code`. Or copy the skill folder (skills/database-design in CloudAI-X/claude-workflow-v2) into .claude/skills/database-design in your project. Claude Code loads it when a task matches its description.
Run `npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -a codex`. Or copy the skill folder (skills/database-design in CloudAI-X/claude-workflow-v2) into .agents/skills/database-design in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add CloudAI-X/claude-workflow-v2 --skill database-design -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-design, .gemini/skills/database-design, .github/skills/database-design and .opencode/skills/database-design in your project.
SKILL.md names no scripts, command-line tools or credentials: Database Design is instructions for the agent only. Our summary lists: Python 3.
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.
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.
Database Design is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.
About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.
Skills that share tags, products or a category with Database Design: SQL Optimization Patterns (ynulihao/AgentSkillOS, 617 stars), DB Migrations (kurealnum/dotfiles, 290 stars), SQL Pro (davila7/claude-code-templates, 32k stars) and Optimizing Ef Core Queries (dotnet/skills, 5.6k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
CloudAI-X (a GitHub user) maintains it in CloudAI-X/claude-workflow-v2, which has 1,418 GitHub stars. The repository holds 13 skills in this directory. The repository was last updated on October 6, 2026.
Source: CloudAI-X/claude-workflow-v2 on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.