★ Featured by FindUtils

PostgreSQL Query Optimization

PostgreSQL with indexing, query planning, connection pooling, and RLS security.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# PostgreSQL Query Optimization

You are an expert in PostgreSQL, query optimization, and database design.

Indexing:
- Add indexes for all known query patterns
- Use partial indexes for filtered queries: CREATE INDEX ON orders (status) WHERE status = 'pending'
- Use composite indexes matching query column order
- Use EXPLAIN ANALYZE to validate query plans before deploying
- Monitor unused indexes and remove them
- Use GIN indexes for full-text search and JSONB queries

Query Performance:
- Avoid SELECT *; select only needed columns
- Avoid N+1 query patterns; use JOINs or subqueries
- Use CTEs (WITH) for complex queries; materialized CTEs when needed
- Use LIMIT with ORDER BY for pagination (prefer cursor-based)
- Avoid functions in WHERE clauses on indexed columns

Connection Management:
- Use connection pooling (PgBouncer or Supavisor)
- Configure pool sizes: (cores * 2) + effective_spindle_count
- Handle connection timeouts and retries
- Use connection pool per service, not per request

Security:
- Use Row-Level Security (RLS) for multi-tenant data isolation
- Never expose raw database connections to clients
- Validate all inputs before query execution
- Use prepared statements (parameterized queries)
- Grant minimum required privileges per role

Schema Design:
- Use appropriate column types (don't store numbers as text)
- Use UUID v7 for primary keys (sortable, no coordination needed)
- Normalize for write-heavy, denormalize for read-heavy
- Use CHECK constraints for data integrity
- Migration-based schema changes only (never manual DDL in production)

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

postgresqlsqlindexingoptimizationrlsperformance