MA

managing-database-partitions

Provides strategies and automation for range, list, and hash partitioning to optimize query performance on large database tables.

Install

mkdir -p .claude/skills/managing-database-partitions && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3842" && unzip -o skill.zip -d .claude/skills/managing-database-partitions && rm skill.zip

Installs to .claude/skills/managing-database-partitions

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Process use when you need to work with database partitioning.
61 chars✓ has a “when” trigger
Advanced

Key capabilities

  • Identify tables exceeding 10GB or 100M rows for partitioning
  • Select partition keys based on common query filter columns
  • Choose partitioning strategies: Range, List, Hash, or Composite
  • Generate DDL scripts for PostgreSQL and MySQL partitioned tables
  • Migrate data from unpartitioned to partitioned tables in batches
  • Automate future partition creation and maintenance with scripts

How it works

This skill identifies partitioning candidates, selects a partition key and strategy, then generates and executes DDL and migration scripts for PostgreSQL or MySQL.

Inputs & outputs

You give it
Table size metrics, query patterns, and desired partitioning strategy
You get back
Partition DDL scripts, data migration scripts, and partition maintenance scripts

When to use managing-database-partitions

  • Partition large time-series tables
  • Optimize query performance for huge datasets
  • Implement data lifecycle management
  • Apply range partitioning by date or ID
  • Configure hash partitioning for distribution

About this skill

Database Partition Manager

Overview

Implement and manage table partitioning for PostgreSQL and MySQL to improve query performance and simplify data lifecycle management on large tables. This skill covers range partitioning (by date or ID), list partitioning (by category or region), hash partitioning (for even distribution), and composite partitioning.

Prerequisites

  • PostgreSQL 10+ (declarative partitioning) or MySQL 5.7+ (native partitioning)
  • Database admin credentials with CREATE TABLE and ALTER TABLE permissions
  • psql or mysql CLI for executing partition DDL
  • Table size metrics: SELECT pg_size_pretty(pg_total_relation_size('table_name')) or SELECT data_length FROM information_schema.TABLES
  • Query patterns on the target table (especially WHERE clause columns used for filtering)
  • Maintenance window availability for initial partition migration on existing tables

Instructions

  1. Identify partitioning candidates by finding tables that exceed 10GB or 100M rows, have time-based query patterns, or require periodic data purging. Query pg_stat_user_tables to find tables with high sequential scan counts on large row sets.

  2. Select the partition key based on the most common query filter column. For time-series data, use the timestamp column. For multi-tenant data, use tenant_id. The partition key must appear in most WHERE clauses to enable partition pruning.

  3. Choose the partitioning strategy:

    • Range: Best for time-series data. Create monthly or daily partitions. Queries filtering by date range scan only relevant partitions.
    • List: Best for categorical data. Create one partition per category, region, or status value.
    • Hash: Best for even distribution when no natural range exists. Distribute rows across N partitions using hash of the partition key.
    • Composite: Combine range + list for multi-dimensional partitioning (e.g., range by date, then list by region).
  4. For PostgreSQL, create the partitioned parent table: CREATE TABLE orders (id bigint, created_at timestamptz, ...) PARTITION BY RANGE (created_at). Then create child partitions: CREATE TABLE orders_2024_01 PARTITION OF orders FOR VALUES FROM ('2024-01-01') TO ('2024-02-01').

  5. For MySQL, define partitions inline: ALTER TABLE orders PARTITION BY RANGE (YEAR(created_at) * 100 + MONTH(created_at)) (PARTITION p202401 VALUES LESS THAN (202402), ...).

  6. Migrate data from an existing unpartitioned table to a partitioned table:

    • Create the new partitioned table with identical schema
    • Copy data in batches: INSERT INTO orders_partitioned SELECT * FROM orders_old WHERE created_at BETWEEN ... AND ...
    • Verify row counts match between old and new tables
    • Rename tables atomically: ALTER TABLE orders RENAME TO orders_old; ALTER TABLE orders_partitioned RENAME TO orders;
  7. Create indexes on each partition. In PostgreSQL, indexes on the parent table automatically propagate to child partitions. Create the primary key and any secondary indexes on the partitioned table.

  8. Automate future partition creation with a scheduled script or cron job. For monthly range partitions, create the next 3 months of partitions in advance to prevent INSERT failures when a new month begins.

  9. Implement partition maintenance: drop or detach old partitions for data retention (ALTER TABLE orders DETACH PARTITION orders_2022_01), then archive or delete the detached partition. This is vastly faster than DELETE FROM orders WHERE created_at < '2023-01-01'.

  10. Verify partition pruning works by running EXPLAIN on typical queries and confirming only relevant partitions are scanned. Look for "Partitions: 1/24" in the plan output indicating effective pruning.

Output

  • Partition DDL scripts for creating partitioned tables and child partitions
  • Data migration scripts for moving data from unpartitioned to partitioned tables
  • Partition maintenance scripts for automated creation, detachment, and archival
  • Partition pruning verification queries confirming optimizer uses partition elimination
  • Cron job configurations for scheduled partition creation and cleanup

Error Handling

ErrorCauseSolution
no partition of relation "table" found for rowINSERT targets a range with no matching partitionCreate the missing partition; implement automated partition pre-creation for future ranges
Partition pruning not occurringQuery filter does not use the partition key, or uses a function on the key columnRewrite query to filter directly on the partition key column; avoid wrapping partition key in functions
Slow data migration from unpartitioned tableSingle large INSERT/SELECT locks the table and fills WALMigrate in batches by partition range; use pg_repack for online migration; increase maintenance_work_mem and max_wal_size
Foreign key references prevent partitioningPostgreSQL does not support foreign keys referencing partitioned tables (pre-v12)Upgrade to PostgreSQL 12+; or remove FK constraints and enforce referential integrity at application level
Too many partitions causing planner slowdownHundreds or thousands of child partitions degrade query planning timeUse wider partition ranges (monthly instead of daily); enable enable_partition_pruning; consider sub-partitioning instead of flat partitioning

Examples

Monthly range partitioning for an events table: A 500GB events table with 2B rows partitioned by created_at into monthly partitions. Queries filtering by date range (last 7 days, last month) now scan only 1-2 partitions instead of the full table. Partition drop replaces a 4-hour DELETE operation with a sub-second DDL command for monthly data purges.

Hash partitioning for a sessions table: A sessions table with random UUID primary keys and no natural range column. Hash partition by session_id across 16 partitions to distribute I/O evenly. Parallel sequential scans across partitions improve full-table analytic queries by 8x on an 8-core server.

Composite partitioning for multi-region SaaS: Orders table partitioned first by range on created_at (monthly), then by list on region (us-east, us-west, eu, asia). Queries for "all US orders this month" prune to just 2 of 48 total partitions, reducing scan volume by 96%.

Resources

When not to use it

  • When foreign key references prevent partitioning in PostgreSQL versions prior to 12
  • When hundreds or thousands of child partitions degrade query planning time

Prerequisites

PostgreSQL 10+ or MySQL 5.7+Database admin credentials with CREATE TABLE and ALTER TABLE permissionspsql or mysql CLITable size metrics and query patterns on the target table

Limitations

  • PostgreSQL does not support foreign keys referencing partitioned tables before version 12
  • Too many partitions can cause planner slowdown

How it compares

This skill automates the generation and execution of partitioning scripts, unlike manual database administration that requires writing each script by hand.

Compared to similar skills

managing-database-partitions side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
managing-database-partitions (this skill)127dReviewAdvanced
sql-optimization-patterns642moNo flagsAdvanced
redis-inspect66moReviewBeginner
supabase-postgres-best-practices46moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

sql-optimization-patterns

wshobson

Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.

64220

redis-inspect

civitai

Inspect Redis cache keys, values, and TTLs for debugging. Supports both main cache and system cache. Use for debugging cache issues, checking cached values, and monitoring cache state. Read-only by default.

646

supabase-postgres-best-practices

davila7

Postgres performance optimization and best practices from Supabase. Use this skill when writing, reviewing, or optimizing Postgres queries, schema designs, or database configurations.

439

supabase-performance-tuning

jeremylongshore

Optimize Supabase API performance with caching, batching, and connection pooling. Use when experiencing slow API responses, implementing caching strategies, or optimizing request throughput for Supabase integrations. Trigger with phrases like "supabase performance", "optimize supabase", "supabase latency", "supabase caching", "supabase slow", "supabase batch".

416

batch-processing

dadbodgeoff

Collect-then-batch pattern for database operations achieving 30-40% throughput improvement. Includes graceful fallback to sequential processing when batch operations fail.

28

analyzing-query-performance

jeremylongshore

Execute use when you need to work with query optimization. This skill provides query performance analysis with comprehensive guidance and automation. Trigger with phrases like "optimize queries", "analyze performance", or "improve query speed".

18

Search skills

Search the agent skills registry