Skip to main content
skillsFirst-partyReview first Safety Privacy

PostgreSQL Query Optimization Skill

Analyze and optimize PostgreSQL queries for OLTP and OLAP workloads with AI-assisted performance tuning, indexing strategies, and execution plan analysis.

HarnessClaude CodeCodexWindsurfGeminiCursorCLI
Level:advancedType:generalVerified:draft
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://www.postgresql.org/docs/current/performance-tips.html, https://github.com/JSONbored/awesome-claude/blob/main/content/skills/postgresql-query-optimization.mdx
Package URL
/downloads/skills/postgresql-query-optimization.zip
Package SHA256
a180b68a318eb007218f5d5de00e12deaf980f75f5e4519eeecc550cba7715df
Safety notes
Setup downloads/unzips a package, and the skill connects to your database to run EXPLAIN ANALYZE and create indexes; index builds and config changes can lock tables and affect production — test against a replica or staging first.
Privacy notes
Query analysis can surface table/column names and sample row values from your database; keep connection strings and credentials in environment variables and review what plans/output you share.
Platform compatibility
claude-code (native-skill), codex (native-skill), windsurf (native-skill), gemini (native-skill), cursor (adapter), cli (manual-context)
Author
JSONbored
Claim status
unclaimed
Last verified
2025-10-16

Decision playbook

Ready to evaluate for your workflow

Signals are comparatively strong, but you should still validate source, privacy posture, and package provenance for your environment.

Compare context
Selected

0

Current score

96

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as first-party.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Complete

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    Package marked verified.

    Done
  • Checksum metadata

    SHA-256 hash is present.

    Done

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Package install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Not provided

Copy snippet

Provided

Prerequisites

6 to clear

Platforms

6 listed

Difficulty

100/100

Adoption plan

Balanced adoption plan

Current risk score 0/100. Use staged verification before broader rollout.

Risk 0

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    Package verification/checksum metadata is available.

    Done

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (6/6 signals complete).

Risk 0

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Present

Package integrity metadata is present.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

6/6 steps complete with no blocking gaps for this preset.

Risk 0

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is available.

Done

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Prerequisite readiness

Prerequisite readiness

6 prerequisites to line up before setup.

0/6 ready
Install & runtime1Permissions & scopes2General3

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, network access.

2 areas
  • SafetyNetwork accessSetup downloads/unzips a package, and the skill connects to your database to run EXPLAIN ANALYZE and create indexes; index builds and config changes can lock tables and affect production — test against a replica or staging first.
  • PrivacyCredentials & tokensQuery analysis can surface table/column names and sample row values from your database; keep connection strings and credentials in environment variables and review what plans/output you share.

Safety notes

  • Setup downloads/unzips a package, and the skill connects to your database to run EXPLAIN ANALYZE and create indexes; index builds and config changes can lock tables and affect production — test against a replica or staging first.

Privacy notes

  • Query analysis can surface table/column names and sample row values from your database; keep connection strings and credentials in environment variables and review what plans/output you share.

Prerequisites

  • PostgreSQL 14+ (16+ recommended)
  • pg_stat_statements extension
  • EXPLAIN access permissions
  • psql or database client
  • PostgreSQL database access with appropriate permissions (SELECT, EXPLAIN, ANALYZE) for query analysis and optimization
  • PostgreSQL version 12+ (recommended 14+) for advanced query optimization features, EXPLAIN ANALYZE, and modern index types

Schema details

Install type
package
Reading time
6 min
Difficulty score
100
Troubleshooting
Yes
Breaking changes
No
Package metadata
Package verified
Yes
SHA-256
a180b68a318eb007218f5d5de00e12deaf980f75f5e4519eeecc550cba7715df
Skill and platform metadata
Skill type
general
Skill level
advanced
Verification
draft
Verified at
2025-10-16
Retrieval sources
https://www.postgresql.org/docs/current/performance-tips.html
Tested platforms
ClaudeCodexOpenClawCursorWindsurfGemini
PlatformSupportInstall path
claude-codeNative.claude/skills/<skill-name>/SKILL.md
codexNative.agents/skills/<skill-name>/SKILL.md
windsurfNative.windsurf/skills/<skill-name>/SKILL.md
geminiNative.gemini/skills/<skill-name>/SKILL.md or .agents/skills/<skill-name>/SKILL.md
cursorAdapter.cursor/rules/<skill-name>.mdc
cliManualAGENTS.md or tool-specific context file
Full copyable content
-- Run with EXPLAIN ANALYZE to get actual execution times
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT p.name, c.name as category, p.price
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.price BETWEEN 100 AND 500
  AND c.name = 'Electronics'
ORDER BY p.created_at DESC
LIMIT 20;

-- Check if indexes are being used
SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY idx_scan ASC;

About this resource

Analyze and optimize PostgreSQL queries for OLTP and OLAP workloads with AI-assisted performance tuning, indexing strategies, and execution plan analysis. Interpret EXPLAIN ANALYZE plans, identify bottlenecks (sequential scans, nested loops, hash joins), design optimal indexes (B-tree, GIN, BRIN, composite, partial), rewrite queries for better performance, and tune database configuration parameters. Includes pg_stat_statements integration for slow query identification, parallel query execution optimization, JIT compilation tuning, advanced partitioning strategies, and vacuum/autovacuum configuration for high-write workloads.

Content

PostgreSQL Query Optimization Skill

What This Skill Enables

Claude can analyze PostgreSQL query performance, interpret EXPLAIN plans, design optimal indexes, and tune database configurations for specific workloads (OLTP, OLAP, or hybrid). With expertise in PostgreSQL 16+ features including parallel query execution, JIT compilation, and advanced partitioning strategies, Claude helps achieve sub-millisecond query times for high-traffic applications.

Compatibility

Native

  • Claude Code / Claude: native skill usage via SKILL.md.
  • Codex/OpenAI workflows: compatible with Agent Skills-style SKILL.md content as reusable workflow instructions.

Manual Adaptation

  • Gemini CLI: native skill usage via .gemini/skills/<skill-name>/SKILL.md or .agents/skills/<skill-name>/SKILL.md where supported.
  • Cursor: use the generated .cursor/rules/*.mdc adapter for project rules.
  • OpenClaw and similar agents: use the same skill content as a reusable prompt/workflow file when native skill import is unavailable.

Prerequisites

Required:

  • Claude Pro subscription or Claude Code CLI
  • PostgreSQL 14+ installed (16+ recommended)
  • Access to database with slow queries or performance issues
  • Basic SQL knowledge

What Claude handles automatically:

  • Analyzing EXPLAIN ANALYZE output
  • Identifying missing or inefficient indexes
  • Suggesting query rewrites for better performance
  • Recommending configuration parameter tuning
  • Detecting N+1 query problems
  • Proposing table partitioning strategies
  • Analyzing vacuum and autovacuum settings
  • Identifying connection pooling needs

How to Use This Skill

Analyze Slow Query

Prompt: "My PostgreSQL query is taking 5 seconds. Here's the query: [paste query]. Analyze the execution plan and suggest optimizations."

Claude will:

  1. Run EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
  2. Identify bottlenecks (seq scans, nested loops)
  3. Suggest missing indexes with CREATE INDEX statements
  4. Rewrite query if needed (JOIN order, subquery optimization)
  5. Estimate performance improvement
  6. Provide before/after comparison

Index Strategy Design

Prompt: "Design an optimal indexing strategy for a high-traffic e-commerce database with 10M products. Include queries: product search by name, filter by category and price range, sort by popularity."

Claude will:

  1. Analyze query patterns and access patterns
  2. Create B-tree indexes for equality/range queries
  3. Add GIN indexes for full-text search
  4. Design composite indexes for multi-column filters
  5. Include partial indexes for filtered queries
  6. Add BRIN indexes for time-series data
  7. Calculate index maintenance overhead

Database Configuration Tuning

Prompt: "Tune PostgreSQL configuration for a 32GB RAM server running high-write OLTP workload with 200 concurrent connections."

Claude will:

  1. Set shared_buffers (25% of RAM = 8GB)
  2. Configure work_mem per connection
  3. Adjust max_connections and connection pooling
  4. Tune WAL settings for write performance
  5. Configure autovacuum for high-write scenarios
  6. Set effective_cache_size
  7. Enable parallel query workers

Query Rewriting for Performance

Prompt: "Rewrite this slow query to eliminate the N+1 problem: [paste ORM-generated query with multiple subqueries]."

Claude will:

  1. Identify N+1 or N+M pattern
  2. Convert subqueries to JOINs
  3. Use CTEs for readability
  4. Apply window functions for ranking
  5. Implement LATERAL joins where appropriate
  6. Add proper indexes for new query
  7. Validate result correctness

Tips for Best Results

  1. Always Use EXPLAIN ANALYZE: Share full EXPLAIN (ANALYZE, BUFFERS) output with Claude. The BUFFERS option reveals I/O patterns crucial for optimization.

  2. Provide Table Schemas: Include CREATE TABLE statements and existing indexes. Claude needs column types and constraints for accurate recommendations.

  3. Share Query Frequency: Mention if a query runs once per day or 10,000 times per second. Optimization strategies differ dramatically.

  4. Workload Type Matters: OLTP (many small transactions) and OLAP (complex analytics) require opposite tuning. Specify your workload.

  5. Include Real Data Volume: "1000 rows" vs "100M rows" changes everything. Share actual table sizes with pg_size_pretty.

  6. Monitor After Changes: Ask Claude to generate monitoring queries to verify improvements don't cause regressions elsewhere.

Common Workflows

Complete Performance Audit

"Perform a comprehensive PostgreSQL performance audit:
1. Identify top 10 slowest queries from pg_stat_statements
2. Analyze EXPLAIN plans for each
3. Detect missing indexes with pg_stat_user_tables
4. Find bloated tables needing VACUUM FULL
5. Review configuration parameters
6. Check for long-running transactions blocking others
7. Provide prioritized optimization action plan"

Time-Series Optimization

"Optimize PostgreSQL for time-series data:
1. 100M rows of sensor data per month
2. Queries filter by device_id and time range
3. Need 90-day retention with automated archival
4. Implement declarative partitioning by month
5. Add BRIN indexes on timestamp columns
6. Configure autovacuum for partition management
7. Create aggregate materialized views"

Full-Text Search Tuning

"Build high-performance full-text search:
1. Search across title, description, tags fields
2. Support phrase queries and ranking
3. Handle 50M documents
4. Sub-100ms query response time
5. Use GIN indexes with tsvector
6. Implement trigram similarity for typo tolerance
7. Add weighted search across columns"

Replication Lag Analysis

"Debug PostgreSQL replication lag:
1. Replica is 30 seconds behind primary
2. Analyze pg_stat_replication metrics
3. Check for long-running queries on replica
4. Identify write-heavy tables causing lag
5. Tune max_wal_senders and wal_keep_size
6. Recommend synchronous vs asynchronous replication
7. Implement connection pooling strategy"

Troubleshooting

Issue: Query still slow after adding index Solution: Index may not be used. Check EXPLAIN plan shows Index Scan (not Seq Scan). Run ANALYZE to update statistics. Consider index-only scans with INCLUDE columns or covering indexes.

Issue: Database running out of connections Solution: Implement connection pooling with PgBouncer or pgpool-II. Reduce max_connections and increase per-connection work_mem. Fix application connection leaks.

Issue: Autovacuum not keeping up Solution: Lower autovacuum_vacuum_scale_factor and autovacuum_vacuum_threshold for high-write tables. Increase autovacuum_max_workers. Consider manual VACUUM during maintenance windows.

Issue: Query fast in development, slow in production Solution: Production has different data distribution. Run ANALYZE on production. Check if production has proper indexes. Compare EXPLAIN plans between environments.

Issue: Disk I/O bottleneck Solution: Increase shared_buffers for caching. Use NVMe SSDs. Consider table partitioning to reduce I/O per query. Implement read replicas for read-heavy workloads.

Issue: Connection pool exhausted Solution: Tune pool size based on connections = ((core_count * 2) + effective_spindle_count). Implement queue_timeout. Add monitoring for pool saturation.

Learn More

Features

  • EXPLAIN plan analysis and visualization with ANALYZE, BUFFERS, VERBOSE options
  • Automatic index recommendation (B-tree, GIN, BRIN, composite, partial, covering indexes)
  • Workload-specific tuning (OLTP vs OLAP configurations)
  • Query rewriting for performance (JOIN optimization, subquery elimination, CTEs, window functions)
  • pg_stat_statements integration for slow query identification and monitoring
  • Parallel query execution optimization with worker configuration
  • JIT compilation tuning for complex analytical queries
  • Advanced partitioning strategies (range, list, hash, composite partitioning)

Use Cases

  • Optimize slow database queries with EXPLAIN plan analysis
  • Design indexing strategies for high-traffic applications
  • Tune PostgreSQL configuration for specific workloads (OLTP/OLAP)
  • Identify and fix N+1 query problems in ORM-generated queries
  • Optimize time-series data queries with BRIN indexes and partitioning
  • Performance audit and monitoring with pg_stat_statements

Source citations

Add this badge to your README

Show that PostgreSQL Query Optimization Skill is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/skills/postgresql-query-optimization.svg)](https://heyclau.de/entry/skills/postgresql-query-optimization)

How it compares

PostgreSQL Query Optimization Skill side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

2 trust signals differ across this comparison (Package trust, Submitter).

Next steps differ across entries — use the actions in the table below to copy install commands and source links per resource.

Field

Analyze and optimize PostgreSQL queries for OLTP and OLAP workloads with AI-assisted performance tuning, indexing strategies, and execution plan analysis.

Open dossier

Expert database architect and optimizer specializing in SQL, NoSQL, performance tuning, and data modeling

Open dossier

Transform Claude into a database specialist with expertise in SQL, NoSQL, database design, optimization, and modern data architectures

Open dossier

Transform Claude into a PostgreSQL specialist with deep knowledge of schema design, indexing, query planning, transactions, and production operations.

Open dossier
Next stepsDiffers
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustDiffersPackage verified2025-10-16Package not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
SubmitterDiffersjaso0n0818
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety · Privacy · Safety · Privacy
Brand
Categoryskillsagentsagentsrules
Sourcefirst-partysource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredjaso0n0818
Added2025-10-162025-09-162025-09-162026-06-16
Platforms
Claude CodeCodexWindsurfGeminiCursorCLI
Claude Code
Claude Code
Claude Code
Source repo
Safety notesSetup downloads/unzips a package, and the skill connects to your database to run EXPLAIN ANALYZE and create indexes; index builds and config changes can lock tables and affect production — test against a replica or staging first.Database operations (migrations, schema changes, DELETE/UPDATE, index builds) can modify or destroy production data and lock tables; review generated SQL and run it against a backup or staging environment first.— missing— missing
Privacy notesQuery analysis can surface table/column names and sample row values from your database; keep connection strings and credentials in environment variables and review what plans/output you share.Database work touches schemas and live data that may include personal or sensitive records, plus connection strings and credentials; keep secrets in environment variables and review what queries read, log, or export.— missingRules reference database URLs and credentials; store connection strings in environment variables or a secrets manager, never in committed application code.
Prerequisites
  • PostgreSQL 14+ (16+ recommended)
  • pg_stat_statements extension
  • EXPLAIN access permissions
  • psql or database client
— none listed— none listed— none listed
Install
curl -L https://heyclau.de/downloads/skills/postgresql-query-optimization.zip -o postgresql-query-optimization.zip && unzip -o postgresql-query-optimization.zip -d ./postgresql-query-optimization
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.