managing-database-partitions

3
0
Source

Process use when you need to work with database partitioning. This skill provides table partitioning strategies with comprehensive guidance and automation. Trigger with phrases like "partition tables", "implement partitioning", or "optimize large tables".

Install

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

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

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

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.