MI

migrate-postgres-tables-to-hypertables

Migrates PostgreSQL tables to TimescaleDB hypertables. Supports planning, partition selection, and migration validation.

Install

mkdir -p .claude/skills/migrate-postgres-tables-to-hypertables && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3048" && unzip -o skill.zip -d .claude/skills/migrate-postgres-tables-to-hypertables && rm skill.zip

Installs to .claude/skills/migrate-postgres-tables-to-hypertables

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.

Use this skill to migrate identified PostgreSQL tables to Timescale/TimescaleDB hypertables with optimal configuration and validation.

**Trigger when user asks to:**
- Migrate or convert PostgreSQL tables to hypertables
- Execute hypertable migration with minimal downtime
- Plan blue-green migration for large tables
- Validate hypertable migration success
- Configure compression after migration

**Prerequisites:** Tables already identified as candidates (use find-hypertable-candidates first if needed)

**Keywords:** migrate to hypertable, convert table, Timescale, TimescaleDB, blue-green migration, in-place conversion, create_hypertable, migration validation, compression setup

Step-by-step migration planning including: partition column selection, chunk interval calculation, PK/constraint handling, migration execution (in-place vs blue-green), and performance validation queries.
892 chars · catalog description✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

Key capabilities

  • Plan partitioning column selection
  • Calculate optimal chunk intervals
  • Manage PK and constraint handling for migration
  • Validate hypertable migration success
  • Configure automatic compression after migration

How it works

It evaluates schema types to identify valid partition keys and generates DDL sequences for conversion, providing SQL for verification of successful implementation.

Inputs & outputs

You give it
Table name for hypertable conversion
You get back
Migration plan, DDL commands, and validation queries

When to use migrate-postgres-tables-to-hypertables

  • Convert existing PostgreSQL table to hypertable
  • Plan blue-green migration for large datasets
  • Configure automatic compression for migrated tables
  • Validate hypertable migration success

About this skill

PostgreSQL to TimescaleDB Hypertable Migration

Migrate identified PostgreSQL tables to TimescaleDB hypertables with optimal configuration, migration planning and validation.

Prerequisites: Tables already identified as hypertable candidates (use companion "find-hypertable-candidates" skill if needed).

Step 1: Optimal Configuration

Partition Column Selection

-- Find potential partition columns
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'your_table_name'
  AND data_type IN ('timestamp', 'timestamptz', 'bigint', 'integer', 'date')
ORDER BY ordinal_position;

Requirements: Time-based (TIMESTAMP/TIMESTAMPTZ/DATE) or sequential integer (INT/BIGINT)

Should represent when the event actually occurred or sequential ordering.

Common choices:

  • timestamp, created_at, event_time - when event occurred
  • id, sequence_number - auto-increment (for sequential data without timestamps)
  • ingested_at - less ideal, only if primary query dimension
  • updated_at - AVOID (records updated out of order, breaks chunk distribution) unless primary query dimension

Special Case: table with BOTH ID AND Timestamp

When table has sequential ID (PK) AND timestamp that correlate:

-- Partition by ID, enable minmax sparse indexes on timestamp
SELECT create_hypertable('orders', 'id', chunk_time_interval => 1000000);
ALTER TABLE orders SET (
    timescaledb.sparse_index = 'minmax(created_at),...'
);

Sparse indexes on time column enable skipping compressed blocks outside queried time ranges.

Use when: ID correlates with time (newer records have higher IDs), need ID-based lookups, time queries also common

Chunk Interval Selection

-- Ensure statistics are current
ANALYZE your_table_name;

-- Estimate index size per time unit
WITH time_range AS (
    SELECT
        MIN(timestamp_column) as min_time,
        MAX(timestamp_column) as max_time,
        EXTRACT(EPOCH FROM (MAX(timestamp_column) - MIN(timestamp_column)))/3600 as total_hours
    FROM your_table_name
),
total_index_size AS (
    SELECT SUM(pg_relation_size(indexname::regclass)) as total_index_bytes
    FROM pg_stat_user_indexes
    WHERE schemaname||'.'||tablename = 'your_schema.your_table_name'
)
SELECT
    pg_size_pretty(tis.total_index_bytes / tr.total_hours) as index_size_per_hour
FROM time_range tr, total_index_size tis;

Target: Indexes of recent chunks < 25% of RAM Default: IMPORTANT: Keep default of 7 days if unsure Range: 1 hour minimum, 30 days maximum

Example: 32GB RAM → target 8GB for recent indexes. If index_size_per_hour = 200MB:

  • 1 hour chunks: 200MB chunk index size × 40 recent = 8GB ✓
  • 6 hour chunks: 1.2GB chunk index size × 7 recent = 8.4GB ✓
  • 1 day chunks: 4.8GB chunk index size × 2 recent = 9.6GB ⚠️ Choose largest interval keeping 2+ recent chunk indexes under target.

Primary Key/ Unique Constraints Compatibility

-- Check existing primary key/ unique constraints
SELECT conname, pg_get_constraintdef(oid) as definition
FROM pg_constraint
WHERE conrelid = 'your_table_name'::regclass AND contype = 'p' OR contype = 'u';

Rules: PK/UNIQUE must include partition column

Actions:

  1. No PK/UNIQUE: No changes needed
  2. PK/UNIQUE includes partition column: No changes needed
  3. PK/UNIQUE excludes partition column: ⚠️ ASK USER PERMISSION to modify PK/UNIQUE

Example: user prompt if needed:

"Primary key (id) doesn't include partition column (timestamp). Must modify to PRIMARY KEY (id, timestamp) to convert to hypertable. This may break application code. Is this acceptable?" "Unique constraint (id) doesn't include partition column (timestamp). Must modify to UNIQUE (id, timestamp) to convert to hypertable. This may break application code. Is this acceptable?"

If the user accepts, modify the constraint:

BEGIN;
ALTER TABLE your_table_name DROP CONSTRAINT existing_pk_name;
ALTER TABLE your_table_name ADD PRIMARY KEY (existing_columns, partition_column);
COMMIT;

If the user does not accept, you should NOT migrate the table.

IMPORTANT: DO NOT modify the primary key/unique constraint without user permission.

Compression Configuration

For detailed segment_by and order_by selection, see "setup-timescaledb-hypertables" skill. Quick reference:

segment_by: Most common WHERE filter with >100 rows per value per chunk

  • IoT: device_id
  • Finance: symbol
  • Analytics: user_id or session_id
-- Analyze cardinality for segment_by selection
SELECT column_name, COUNT(DISTINCT column_name) as unique_values,
       ROUND(COUNT(*)::float / COUNT(DISTINCT column_name), 2) as avg_rows_per_value
FROM your_table_name GROUP BY column_name;

order_by: Usually timestamp DESC. The (segment_by, order_by) combination should form a natural time-series progression.

  • If column has <100 rows/chunk (too low for segment_by), prepend to order_by: order_by='low_density_col, timestamp DESC'

sparse indexes: add minmax on the columns that are used in the WHERE clauses but are not in the segment_by or order_by. Use minmax for columns used in range queries.

ALTER TABLE your_table_name SET (
    timescaledb.enable_columnstore,
    timescaledb.segmentby = 'entity_id',
    timescaledb.orderby = 'timestamp DESC'
    timescaledb.sparse_index = 'minmax(value_1),...'
);

-- Compress after data unlikely to change (adjust `after` parameter based on update patterns)
CALL add_columnstore_policy('your_table_name', after => INTERVAL '7 days');

Step 2: Migration Planning

Pre-Migration Checklist

  • Partition column selected
  • Chunk interval calculated (or using default)
  • PK includes partition column OR user approved modification
  • No Hypertable→Hypertable foreign keys
  • Unique constraints include partition column
  • Created compression configuration (segment_by, order_by, sparse indexes, compression policy)
  • Maintenance window scheduled / backup created.

Migration Options

Option 1: In-Place (Tables < 1GB)

-- Enable extension
CREATE EXTENSION IF NOT EXISTS timescaledb;

-- Convert to hypertable (locks table)
SELECT create_hypertable(
    'your_table_name',
    'timestamp_column',
    chunk_time_interval => INTERVAL '7 days',
    if_not_exists => TRUE
);

-- Configure compression
ALTER TABLE your_table_name SET (
    timescaledb.enable_columnstore,
    timescaledb.segmentby = 'entity_id',
    timescaledb.orderby = 'timestamp DESC',
    timescaledb.sparse_index = 'minmax(value_1),...'
);

-- Adjust `after` parameter based on update patterns
CALL add_columnstore_policy('your_table_name', after => INTERVAL '7 days');

Option 2: Blue-Green (Tables > 1GB)

-- 1. Create new hypertable
CREATE TABLE your_table_name_new (LIKE your_table_name INCLUDING ALL);

-- 2. Convert to hypertable
SELECT create_hypertable('your_table_name_new', 'timestamp_column');

-- 3. Configure compression
ALTER TABLE your_table_name_new SET (
    timescaledb.enable_columnstore,
    timescaledb.segmentby = 'entity_id',
    timescaledb.orderby = 'timestamp DESC'
);

-- 4. Migrate data in batches
INSERT INTO your_table_name_new
SELECT * FROM your_table_name
WHERE timestamp_column >= '2024-01-01' AND timestamp_column < '2024-02-01';
-- Repeat for each time range

-- 4. Enter maintenance window and do the following:

-- 5. Pause modification of the old table.

-- 6. Copy over the most recent data from the old table to the new table.

-- 7. Swap tables
BEGIN;
ALTER TABLE your_table_name RENAME TO your_table_name_old;
ALTER TABLE your_table_name_new RENAME TO your_table_name;
COMMIT;

-- 8. Exit maintenance window.

-- 9. (sometime much later) Drop old table after validation
-- DROP TABLE your_table_name_old;

Common Issues

Foreign Keys

-- Check foreign keys
SELECT conname, confrelid::regclass as referenced_table
FROM pg_constraint
WHERE (conrelid = 'your_table_name'::regclass
    OR confrelid = 'your_table_name'::regclass)
  AND contype = 'f';

Supported: Plain→Hypertable, Hypertable→Plain NOT supported: Hypertable→Hypertable

⚠️ CRITICAL: Hypertable→Hypertable FKs must be dropped (enforce in application). ASK USER PERMISSION. If no, STOP MIGRATION.

Large Table Migration Time

-- Rough estimate: ~75k rows/second
SELECT
    pg_size_pretty(pg_total_relation_size(tablename)) as size,
    n_live_tup as rows,
    ROUND(n_live_tup / 75000.0 / 60, 1) as estimated_minutes
FROM pg_stat_user_tables
WHERE tablename = 'your_table_name';

Solutions for large tables (>1GB/10M rows): Use blue-green migration, migrate during off-peak, test on subset first

Step 3: Performance Validation

Chunk & Compression Analysis

-- View chunks and compression
SELECT
    chunk_name,
    pg_size_pretty(total_bytes) as size,
    pg_size_pretty(compressed_total_bytes) as compressed_size,
    ROUND((total_bytes - compressed_total_bytes::numeric) / total_bytes * 100, 1) as compression_pct,
    range_start,
    range_end
FROM timescaledb_information.chunks
WHERE hypertable_name = 'your_table_name'
ORDER BY range_start DESC;

Look for:

  • Consistent chunk sizes (within 2x)
  • Compression >90% for time-series
  • Recent chunks uncompressed
  • Chunk indexes < 25% RAM

Query Performance Tests

-- 1. Time-range query (should show chunk exclusion)
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*), AVG(value)
FROM your_table_name
WHERE timestamp >= NOW() - INTERVAL '1 day';

-- 2. Entity + time query (benefits from segment_by)
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM your_table_name
WHERE entity_id = 'X' AND timestamp >= NOW() - INTERVAL '1 week';

-- 3. Aggregation (benefits from columnstore)
EXPLAIN (ANALYZE, BUFFERS)
SELECT DATE_TRUNC('hour', timestamp), entity_id, COUNT(*), AVG(value)
FROM your_table_name
WHERE timestamp >= NOW() - INTERVAL '1 month'
GROUP BY 1, 2;

*✅ Good signs:


Content truncated.

When not to use it

  • Tables without time-series or sequential data
  • Systems with incompatible PostgreSQL versions

Prerequisites

PostgreSQL 15+TimescaleDB extension installed

Limitations

  • Requires careful column selection to prevent performance issues
  • Cannot migrate columns with non-sequential or out-of-order data easily
  • Requires downtime considerations for large datasets

How it compares

Provides a structured migration plan for TimescaleDB rather than generic SQL optimization advice.

Compared to similar skills

migrate-postgres-tables-to-hypertables side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
migrate-postgres-tables-to-hypertables (this skill)14moNo flagsAdvanced
databases19moReviewIntermediate
sql-optimization-patterns642moNo flagsAdvanced
drizzle-orm322moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by timescale

View all by timescale

pgvector-semantic-search

timescale

Use this skill for setting up vector similarity search with pgvector for AI/ML embeddings, RAG applications, or semantic search. **Trigger when user asks to:** - Store or search vector embeddings in PostgreSQL - Set up semantic search, similarity search, or nearest neighbor search - Create HNSW or IVFFlat indexes for vectors - Implement RAG (Retrieval Augmented Generation) with PostgreSQL - Optimize pgvector performance, recall, or memory usage - Use binary quantization for large vector datasets **Keywords:** pgvector, embeddings, semantic search, vector similarity, HNSW, IVFFlat, halfvec, cosine distance, nearest neighbor, RAG, LLM, AI search Covers: halfvec storage, HNSW index configuration (m, ef_construction, ef_search), quantization strategies, filtered search, bulk loading, and performance tuning.

423

design-postgres-tables

timescale

Use this skill for general PostgreSQL table design. **Trigger when user asks to:** - Design PostgreSQL tables, schemas, or data models when creating new tables and when modifying existing ones. - Choose data types, constraints, or indexes for PostgreSQL - Create user tables, order tables, reference tables, or JSONB schemas - Understand PostgreSQL best practices for normalization, constraints, or indexing - Design update-heavy, upsert-heavy, or OLTP-style tables **Keywords:** PostgreSQL schema, table design, data types, PRIMARY KEY, FOREIGN KEY, indexes, B-tree, GIN, JSONB, constraints, normalization, identity columns, partitioning, row-level security Comprehensive reference covering data types, indexing strategies, constraints, JSONB patterns, partitioning, and PostgreSQL-specific best practices.

323

find-hypertable-candidates

timescale

Use this skill to analyze an existing PostgreSQL database and identify which tables should be converted to Timescale/TimescaleDB hypertables. **Trigger when user asks to:** - Analyze database tables for hypertable conversion potential - Identify time-series or event tables in an existing schema - Evaluate if a table would benefit from Timescale/TimescaleDB - Audit PostgreSQL tables for migration to Timescale/TimescaleDB/TigerData - Score or rank tables for hypertable candidacy **Keywords:** hypertable candidate, table analysis, migration assessment, Timescale, TimescaleDB, time-series detection, insert-heavy tables, event logs, audit tables Provides SQL queries to analyze table statistics, index patterns, and query patterns. Includes scoring criteria (8+ points = good candidate) and pattern recognition for IoT, events, transactions, and sequential data.

18

postgres-hybrid-text-search

timescale

Use this skill to implement hybrid search combining BM25 keyword search with semantic vector search using Reciprocal Rank Fusion (RRF). **Trigger when user asks to:** - Combine keyword and semantic search - Implement hybrid search or multi-modal retrieval - Use BM25/pg_textsearch with pgvector together - Implement RRF (Reciprocal Rank Fusion) for search - Build search that handles both exact terms and meaning **Keywords:** hybrid search, BM25, pg_textsearch, RRF, reciprocal rank fusion, keyword search, full-text search, reranking, cross-encoder Covers: pg_textsearch BM25 index setup, parallel query patterns, client-side RRF fusion (Python/TypeScript), weighting strategies, and optional ML reranking.

112

setup-timescaledb-hypertables

timescale

Use this skill when creating database schemas or tables for Timescale, TimescaleDB, TigerData, or Tiger Cloud, especially for time-series, IoT, metrics, events, or log data. Use this to improve the performance of any insert-heavy table. **Trigger when user asks to:** - Create or design SQL schemas/tables AND Timescale/TimescaleDB/TigerData/Tiger Cloud is available - Set up hypertables, compression, retention policies, or continuous aggregates - Configure partition columns, segment_by, order_by, or chunk intervals - Optimize time-series database performance or storage - Create tables for sensors, metrics, telemetry, events, or transaction logs **Keywords:** CREATE TABLE, hypertable, Timescale, TimescaleDB, time-series, IoT, metrics, sensor data, compression policy, continuous aggregates, columnstore, retention policy, chunk interval, segment_by, order_by Step-by-step instructions for hypertable creation, column selection, compression policies, retention, continuous aggregates, and indexes.

05

You might also like

databases

mrgoonie

Work with MongoDB (document database, BSON documents, aggregation pipelines, Atlas cloud) and PostgreSQL (relational database, SQL queries, psql CLI, pgAdmin). Use when designing database schemas, writing queries and aggregations, optimizing indexes for performance, performing database migrations, configuring replication and sharding, implementing backup and restore strategies, managing database users and permissions, analyzing query performance, or administering production databases.

16

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

drizzle-orm

EpicenterHQ

Drizzle ORM patterns for type branding and custom types. Use when working with Drizzle column definitions, branded types, or custom type conversions.

32190

database-design

davila7

Database design principles and decision-making. Schema design, indexing strategy, ORM selection, serverless databases.

648

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

database-schema-designer

davila7

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

628

Search skills

Search the agent skills registry