postgresql
PostgreSQL
Section titled “PostgreSQL”Description
Section titled “Description”PostgreSQL database patterns including queries, indexing, and optimization.
When to Use
Section titled “When to Use”- PostgreSQL database operations
- SQL query optimization
- Schema design
Core Patterns
Section titled “Core Patterns”Basic Queries
Section titled “Basic Queries”-- Select with filteringSELECT id, name, emailFROM usersWHERE active = trueORDER BY created_at DESCLIMIT 20 OFFSET 0;
-- JoinSELECT u.*, COUNT(p.id) as post_countFROM users uLEFT JOIN posts p ON p.user_id = u.idGROUP BY u.id;Indexes
Section titled “Indexes”-- Single column indexCREATE INDEX idx_users_email ON users(email);
-- Composite indexCREATE INDEX idx_posts_user_date ON posts(user_id, created_at DESC);
-- Partial indexCREATE INDEX idx_active_users ON users(email) WHERE active = true;Migrations
Section titled “Migrations”-- Add column with defaultALTER TABLE users ADD COLUMN role VARCHAR(50) DEFAULT 'user';
-- Add constraintALTER TABLE users ADD CONSTRAINT unique_email UNIQUE (email);Best Practices
Section titled “Best Practices”- Use indexes for filtered/sorted columns
- Use EXPLAIN ANALYZE for slow queries
- Avoid SELECT * in production
- Use transactions for multiple operations
- Use connection pooling
Common Pitfalls
Section titled “Common Pitfalls”- N+1 queries: Use JOINs or batch loading
- Missing indexes: Add indexes for WHERE/ORDER BY
- Large transactions: Keep transactions short
Gap Analysis Rule
Section titled “Gap Analysis Rule”Always identify gaps and suggest next steps to users. In case there is no gaps anymore, then AI should clearly state that there is no gap left.