Database Optimization logo

Database Optimization

CommunityPopular
rohitg00
database-optimization

Query optimization, indexing strategies, and database performance tuning for PostgreSQL and MySQL

Overview

Publisherrohitg00
Repositoryawesome-claude-code-toolkit
Skill namedatabase-optimization
Stars
2.6K
Forks
963
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by rohitg00 on GitHub. Read the source before you install it.

Installation

Install the Database Optimization AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/rohitg00/awesome-claude-code-toolkit.git /tmp/awesome-claude-code-toolkit
mkdir -p .claude/skills
cp -r /tmp/awesome-claude-code-toolkit/skills/database-optimization .claude/skills/database-optimization
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Database Optimization in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Database Optimization on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Database Optimization is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Database Optimization

EXPLAIN Analysis

Always run EXPLAIN ANALYZE before optimizing. Read the output bottom-up.

sql
-- PostgreSQL
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;

-- MySQL
EXPLAIN ANALYZE SELECT ...;

Key metrics to watch:

  • Seq Scan on large tables = missing index
  • Nested Loop with high row count = consider hash/merge join
  • Sort without index = add index on sort column
  • Rows estimated vs actual divergence = stale statistics, run ANALYZE

Index Strategies

B-tree (default, most cases)

sql
CREATE INDEX idx_users_email ON users (email);
CREATE INDEX idx_orders_user_date ON orders (user_id, created_at DESC);

Use for: equality, range queries, sorting. Column order matters in composite indexes: put equality columns first, then range/sort columns.

Partial Index (PostgreSQL)

sql
CREATE INDEX idx_orders_pending ON orders (created_at)
  WHERE status = 'pending';

Use when queries always filter on a specific condition. Dramatically smaller than full indexes.

GIN (PostgreSQL - arrays, JSONB, full-text)

sql
CREATE INDEX idx_products_tags ON products USING GIN (tags);
CREATE INDEX idx_docs_search ON documents USING GIN (to_tsvector('english', content));

GiST (PostgreSQL - spatial, range types)

sql
CREATE INDEX idx_locations_point ON locations USING GiST (coordinates);
CREATE INDEX idx_events_period ON events USING GiST (tsrange(start_at, end_at));

Covering Index (index-only scans)

sql
-- PostgreSQL
CREATE INDEX idx_users_email_name ON users (email) INCLUDE (name);

-- MySQL
CREATE INDEX idx_users_email_name ON users (email, name);

N+1 Query Detection

Symptom: 1 query to fetch parent + N queries for each child.

python
# BAD: N+1
users = db.query(User).all()
for user in users:
    print(user.orders)  # triggers query per user

# GOOD: eager load
users = db.query(User).options(joinedload(User.orders)).all()
javascript
// BAD: N+1
const users = await User.findAll();
for (const user of users) {
  const orders = await Order.findAll({ where: { userId: user.id } });
}

// GOOD: batch load
const users = await User.findAll({ include: [Order] });

Detection: enable query logging, count queries per request. More than 10 queries for a single endpoint is a red flag.

Connection Pooling

Rule of thumb: pool_size = (core_count * 2) + disk_count
Typical web app: 10-20 connections per app instance

PostgreSQL:

  • Use PgBouncer in transaction mode for serverless/high-connection scenarios
  • Set idle_in_transaction_session_timeout = '30s'
  • Monitor with pg_stat_activity

MySQL:

  • Set max_connections based on available RAM (each connection uses ~10MB)
  • Use ProxySQL for connection multiplexing
  • Monitor with SHOW PROCESSLIST

Read Replicas

  • Route all SELECT queries to replicas
  • Route all writes to primary
  • Account for replication lag (typically 10-100ms)
  • Never read-after-write from a replica; use primary for consistency-critical reads
  • Use connection-level routing, not query-level
python
# SQLAlchemy read replica routing
class RoutingSession(Session):
    def get_bind(self, mapper=None, clause=None):
        if self._flushing or self.is_modified():
            return engines["primary"]
        return engines["replica"]

Partition Strategies

Range Partitioning (time-series data)

sql
-- PostgreSQL
CREATE TABLE events (
    id bigint GENERATED ALWAYS AS IDENTITY,
    created_at timestamptz NOT NULL,
    data jsonb
) PARTITION BY RANGE (created_at);

CREATE TABLE events_2025_q1 PARTITION OF events
    FOR VALUES FROM ('2025-01-01') TO ('2025-04-01');
CREATE TABLE events_2025_q2 PARTITION OF events
    FOR VALUES FROM ('2025-04-01') TO ('2025-07-01');

Hash Partitioning (even distribution)

sql
CREATE TABLE sessions (
    id uuid PRIMARY KEY,
    user_id bigint NOT NULL
) PARTITION BY HASH (user_id);

CREATE TABLE sessions_0 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE sessions_1 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 1);

Partition when tables exceed 50-100GB or when you need to drop old data quickly.

Query Optimization Checklist

  1. Run EXPLAIN ANALYZE and read the plan
  2. Check for sequential scans on tables with >10K rows
  3. Verify index usage (check idx_scan in pg_stat_user_indexes)
  4. Look for implicit type casts that prevent index use
  5. Replace SELECT * with specific columns
  6. Add LIMIT to queries that only need a subset
  7. Use EXISTS instead of COUNT(*) > 0
  8. Batch INSERT/UPDATE operations (500-1000 rows per batch)
  9. Avoid functions on indexed columns in WHERE clauses
  10. Monitor slow query log (pg: log_min_duration_statement = 100)

Dangerous Patterns

  • LIKE '%term%' on unindexed columns (use full-text search instead)
  • ORDER BY RANDOM() (use TABLESAMPLE or application-level randomization)
  • SELECT DISTINCT masking a join problem
  • Missing WHERE on UPDATE/DELETE (always verify with SELECT first)
  • Long-running transactions holding locks
  • Using OFFSET for deep pagination (use keyset/cursor pagination instead)

Frequently asked questions

What does the Database Optimization AI skill do?

Query optimization, indexing strategies, and database performance tuning for PostgreSQL and MySQL

Why use Database Optimization on TypingMind?

Because you install it once and use it with any model. Database Optimization is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Database Optimization in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/rohitg00/awesome-claude-code-toolkit/tree/main/skills/database-optimization. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Database Optimization?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Database Optimization?

As many as you like. As long as a model supports skills, you can use Database Optimization with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Database Optimization AI skill free?

Yes. It is published on GitHub by rohitg00 under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇