Overview
PostgreSQL query optimization and schema design. Covers EXPLAIN ANALYZE, index types, query rewriting, partitioning, and connection pooling.
Capabilities
- Analyze query performance with EXPLAIN ANALYZE
- Design optimal indexes (B-tree, GIN, GiST, BRIN)
- Optimize slow queries through rewriting and restructuring
- Implement table partitioning for large datasets
- Configure connection pooling (PgBouncer, Supabase Pooler)
When to Use
Trigger phrases:
"postgres queries"
"PostgreSQL optimization — query tuning, schema design, indexing strategies, and "
Queries taking >100ms that should be <10ms
Database CPU or I/O is a bottleneck
Designing schema for a new high-traffic feature
Planning partitioning strategy for large tables
When NOT to Use
- Task is about deployment, not development (use deploy skills)
- Task is about code review, not writing (use review skills)
- You need to understand existing code first (use research skills)
- Task is about testing only (use test skills)
- Requirements are unclear (clarify first)
- Task is trivially simple (single line fix)
Pseudo Code
The postgres-queries workflow follows a standard pipeline pattern.
Core flow:
# postgres-queries primary flow
input = prepare(raw_data)
result = process(input, config={analysis, design, indexing, optimization, performance})
validate(result)
deliver(result)
Error handling:
on error:
log(error_details)
retry_with_backoff(max=3)
if still_failing: alert_and_escalate()
EXPLAIN ANALYZE
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT u.name, COUNT(o.id)
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE o.created_at > NOW() - INTERVAL '30 days'
GROUP BY u.name;
Index Strategy
-- Composite index for common query pattern
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);
-- Partial index for active records
CREATE INDEX idx_active_users ON users(email) WHERE deleted_at IS NULL;
-- GIN index for JSONB
CREATE INDEX idx_metadata ON products USING GIN(metadata);
Common Patterns
- EXPLAIN first: Always EXPLAIN ANALYZE before optimizing
- Composite indexes: Column order matters — put equality columns first, range last
- Partial indexes: Index only rows you query frequently
- Connection pooling: Use PgBouncer for >100 concurrent connections
How to Use
- Understand the requirement and existing codebase patterns
- Design the solution with error handling and testability in mind
- Implement incrementally with tests for each change
- Verify against expected outcomes (manual and automated)
- Document usage, edge cases, and integration points
- Review with team before merging to shared branches
Red Flags
- Skipping tests to ship faster: Untested code breaks in production when you least expect it
- No error handling in production code: Unhandled errors crash services and lose user data
- Hardcoded configuration values: Hardcoded values prevent environment switching and leak secrets
- Ignoring security implications: Missing input validation, auth bypasses, and injection vulnerabilities
- Over-engineering simple solutions: Premature abstraction adds complexity without proportional benefit
Verification
Process
- Analyze the task requirements
- Apply domain expertise
- Verify output quality
Anti-Rationalization Table
| Rationalization |
Reality |
| "Tests slow me down" |
Bugs slow you down 10x more. Tests are speed, not overhead. |
| "I will refactor later" |
Technical debt compounds. Refactor as you go. |
| "It works on my machine" |
If it is not in CI, it does not work. Ship proof, not claims. |
1---2name: postgres-queries3description: Use when postgreSQL optimization — query tuning, schema design, indexing4 strategies, and performance analysis. Use when working with postgres queries.5domain: development6author: oyi777license: Apache-2.08subdomain: software-development9tags:10- coding11- postgres12- queries13- software-engineering14- testing15version: 1.0.016category: development17metadata:18 source: https://skillmd.com/skills/oyi77/postgres-queries19---20212223## Overview2425PostgreSQL query optimization and schema design. Covers EXPLAIN ANALYZE, index types, query rewriting, partitioning, and connection pooling.2627## Capabilities2829- Analyze query performance with EXPLAIN ANALYZE30- Design optimal indexes (B-tree, GIN, GiST, BRIN)31- Optimize slow queries through rewriting and restructuring32- Implement table partitioning for large datasets33- Configure connection pooling (PgBouncer, Supabase Pooler)3435## When to Use36**Trigger phrases:**37- "postgres queries"38- "PostgreSQL optimization — query tuning, schema design, indexing strategies, and "394041- Queries taking >100ms that should be <10ms42- Database CPU or I/O is a bottleneck43- Designing schema for a new high-traffic feature44- Planning partitioning strategy for large tables4546## When NOT to Use4748- Task is about deployment, not development (use deploy skills)49- Task is about code review, not writing (use review skills)50- You need to understand existing code first (use research skills)51- Task is about testing only (use test skills)52- Requirements are unclear (clarify first)53- Task is trivially simple (single line fix)545556## Pseudo Code5758The postgres-queries workflow follows a standard pipeline pattern.5960Core flow:61```62# postgres-queries primary flow63input = prepare(raw_data)64result = process(input, config={analysis, design, indexing, optimization, performance})65validate(result)66deliver(result)67```6869Error handling:70```71on error:72 log(error_details)73 retry_with_backoff(max=3)74 if still_failing: alert_and_escalate()75```767778### EXPLAIN ANALYZE79```sql80EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)81SELECT u.name, COUNT(o.id)82FROM users u83JOIN orders o ON o.user_id = u.id84WHERE o.created_at > NOW() - INTERVAL '30 days'85GROUP BY u.name;86```8788### Index Strategy89```sql90-- Composite index for common query pattern91CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);9293-- Partial index for active records94CREATE INDEX idx_active_users ON users(email) WHERE deleted_at IS NULL;9596-- GIN index for JSONB97CREATE INDEX idx_metadata ON products USING GIN(metadata);98```99100## Common Patterns101102- **EXPLAIN first**: Always EXPLAIN ANALYZE before optimizing103- **Composite indexes**: Column order matters — put equality columns first, range last104- **Partial indexes**: Index only rows you query frequently105- **Connection pooling**: Use PgBouncer for >100 concurrent connections106107## How to Use1081091. Understand the requirement and existing codebase patterns1102. Design the solution with error handling and testability in mind1113. Implement incrementally with tests for each change1124. Verify against expected outcomes (manual and automated)1135. Document usage, edge cases, and integration points1146. Review with team before merging to shared branches115116## Red Flags117118- **Skipping tests to ship faster**: Untested code breaks in production when you least expect it119- **No error handling in production code**: Unhandled errors crash services and lose user data120- **Hardcoded configuration values**: Hardcoded values prevent environment switching and leak secrets121- **Ignoring security implications**: Missing input validation, auth bypasses, and injection vulnerabilities122- **Over-engineering simple solutions**: Premature abstraction adds complexity without proportional benefit123124## Verification125126- [ ] Skill output matches expected behavior127128## Process1291301. Analyze the task requirements1312. Apply domain expertise1323. Verify output quality133134## Anti-Rationalization Table135136| Rationalization | Reality |137|---|---|138| "Tests slow me down" | Bugs slow you down 10x more. Tests are speed, not overhead. |139| "I will refactor later" | Technical debt compounds. Refactor as you go. |140| "It works on my machine" | If it is not in CI, it does not work. Ship proof, not claims. |