1
---
2
name: postgresql-optimization
3
description: 'PostgreSQL-specific development assistant focusing on unique PostgreSQL features, advanced data types, and PostgreSQL-exclusive capabilities. Covers JSONB operations, array types, custom types, range/geometric types, full-text search, window functions, and PostgreSQL extensions ecosystem.'
4
---
5
6
# PostgreSQL Development Assistant
7
8
Expert PostgreSQL guidance for ${selection} (or entire project if no selection). Focus on PostgreSQL-specific features, optimization patterns, and advanced capabilities.
9
10
## PostgreSQL-Specific Features
11
12
### JSONB Operations
13
```sql
14
-- Advanced JSONB queries
15
CREATE TABLE events (
16
id SERIAL PRIMARY KEY,
17
data JSONB NOT NULL,
18
created_at TIMESTAMPTZ DEFAULT NOW()
19
);
20
21
-- GIN index for JSONB performance
22
CREATE INDEX idx_events_data_gin ON events USING gin(data);
23
24
-- JSONB containment and path queries
25
SELECT * FROM events
26
WHERE data @> '{"type": "login"}'
27
AND data #>> '{user,role}' = 'admin';
28
29
-- JSONB aggregation
30
SELECT jsonb_agg(data) FROM events WHERE data ? 'user_id';
31
```
32
33
### Array Operations
34
```sql
35
-- PostgreSQL arrays
36
CREATE TABLE posts (
37
id SERIAL PRIMARY KEY,
38
tags TEXT[],
39
categories INTEGER[]
40
);
41
42
-- Array queries and operations
43
SELECT * FROM posts WHERE 'postgresql' = ANY(tags);
44
SELECT * FROM posts WHERE tags && ARRAY['database', 'sql'];
45
SELECT * FROM posts WHERE array_length(tags, 1) > 3;
46
47
-- Array aggregation
48
SELECT array_agg(DISTINCT category) FROM posts, unnest(categories) as category;
49
```
50
51
### Window Functions & Analytics
52
```sql
53
-- Advanced window functions
54
SELECT
55
product_id,
56
sale_date,
57
amount,
58
-- Running totals
59
SUM(amount) OVER (PARTITION BY product_id ORDER BY sale_date) as running_total,
60
-- Moving averages
61
AVG(amount) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as moving_avg,
62
-- Rankings
63
DENSE_RANK() OVER (PARTITION BY EXTRACT(month FROM sale_date) ORDER BY amount DESC) as monthly_rank,
64
-- Lag/Lead for comparisons
65
LAG(amount, 1) OVER (PARTITION BY product_id ORDER BY sale_date) as prev_amount
66
FROM sales;
67
```
68
69
### Full-Text Search
70
```sql
71
-- PostgreSQL full-text search
72
CREATE TABLE documents (
73
id SERIAL PRIMARY KEY,
74
title TEXT,
75
content TEXT,
76
search_vector tsvector
77
);
78
79
-- Update search vector
80
UPDATE documents
81
SET search_vector = to_tsvector('english', title || ' ' || content);
82
83
-- GIN index for search performance
84
CREATE INDEX idx_documents_search ON documents USING gin(search_vector);
85
86
-- Search queries
87
SELECT * FROM documents
88
WHERE search_vector @@ plainto_tsquery('english', 'postgresql database');
89
90
-- Ranking results
91
SELECT *, ts_rank(search_vector, plainto_tsquery('postgresql')) as rank
92
FROM documents
93
WHERE search_vector @@ plainto_tsquery('postgresql')
94
ORDER BY rank DESC;
95
```
96
97
## PostgreSQL Performance Tuning
98
99
### Query Optimization
100
```sql
101
-- EXPLAIN ANALYZE for performance analysis
102
-- Note: ANALYZE actually executes the statement. For INSERT/UPDATE/DELETE,
103
-- run it inside BEGIN ... ROLLBACK so the changes are not kept.
104
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
105
SELECT u.name, COUNT(o.id) as order_count
106
FROM users u
107
LEFT JOIN orders o ON u.id = o.user_id
108
WHERE u.created_at > '2024-01-01'::date
109
GROUP BY u.id, u.name;
110
111
-- Identify slow queries from pg_stat_statements
112
-- (PostgreSQL 13+; on 12 and earlier the columns are total_time and mean_time)
113
SELECT query, calls, total_exec_time, mean_exec_time, rows,
114
100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent
115
FROM pg_stat_statements
116
ORDER BY total_exec_time DESC
117
LIMIT 10;
118
```
119
120
### Index Strategies
121
```sql
122
-- Composite indexes for multi-column queries
123
CREATE INDEX idx_orders_user_date ON orders(user_id, order_date);
124
125
-- Partial indexes for filtered queries
126
CREATE INDEX idx_active_users ON users(created_at) WHERE status = 'active';
127
128
-- Expression indexes for computed values
129
CREATE INDEX idx_users_lower_email ON users(lower(email));
130
131
-- Covering indexes to avoid table lookups
132
CREATE INDEX idx_orders_covering ON orders(user_id, status) INCLUDE (total, created_at);
133
```
134
135
### Connection & Memory Management
136
```sql
137
-- Check connection usage
138
SELECT count(*) as connections, state
139
FROM pg_stat_activity
140
GROUP BY state;
141
142
-- Monitor memory usage
143
SELECT name, setting, unit
144
FROM pg_settings
145
WHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem');
146
```
147
148
## PostgreSQL Advanced Data Types
149
150
### Custom Types & Domains
151
```sql
152
-- Create custom types
153
CREATE TYPE address_type AS (
154
street TEXT,
155
city TEXT,
156
postal_code TEXT,
157
country TEXT
158
);
159
160
CREATE TYPE order_status AS ENUM ('pending', 'processing', 'shipped', 'delivered', 'cancelled');
161
162
-- Use domains for data validation
163
CREATE DOMAIN email_address AS TEXT
164
CHECK (VALUE ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');
165
166
-- Table using custom types
167
CREATE TABLE customers (
168
id SERIAL PRIMARY KEY,
169
email email_address NOT NULL,
170
address address_type,
171
status order_status DEFAULT 'pending'
172
);
173
```
174
175
### Range Types
176
```sql
177
-- PostgreSQL range types
178
CREATE TABLE reservations (
179
id SERIAL PRIMARY KEY,
180
room_id INTEGER,
181
reservation_period tstzrange,
182
price_range numrange
183
);
184
185
-- Range queries
186
SELECT * FROM reservations
187
WHERE reservation_period && tstzrange('2024-07-20', '2024-07-25');
188
189
-- Exclude overlapping ranges
190
ALTER TABLE reservations
191
ADD CONSTRAINT no_overlap
192
EXCLUDE USING gist (room_id WITH =, reservation_period WITH &&);
193
```
194
195
### Geometric Types
196
```sql
197
-- PostgreSQL geometric types
198
CREATE TABLE locations (
199
id SERIAL PRIMARY KEY,
200
name TEXT,
201
coordinates POINT,
202
coverage CIRCLE,
203
service_area POLYGON
204
);
205
206
-- Geometric queries
207
SELECT name FROM locations
208
WHERE coordinates <-> point(40.7128, -74.0060) < 10; -- Within 10 units
209
210
-- GiST index for geometric data
211
CREATE INDEX idx_locations_coords ON locations USING gist(coordinates);
212
```
213
214
## 📊 PostgreSQL Extensions & Tools
215
216
### Useful Extensions
217
```sql
218
-- Enable commonly used extensions
219
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- UUID generation
220
CREATE EXTENSION IF NOT EXISTS "pgcrypto"; -- Cryptographic functions
221
CREATE EXTENSION IF NOT EXISTS "unaccent"; -- Remove accents from text
222
CREATE EXTENSION IF NOT EXISTS "pg_trgm"; -- Trigram matching
223
CREATE EXTENSION IF NOT EXISTS "btree_gin"; -- GIN indexes for btree types
224
225
-- Using extensions
226
SELECT uuid_generate_v4(); -- Generate UUIDs
227
SELECT crypt('password', gen_salt('bf')); -- Hash passwords
228
SELECT similarity('postgresql', 'postgersql'); -- Fuzzy matching
229
```
230
231
### Monitoring & Maintenance
232
```sql
233
-- Database size and growth
234
SELECT pg_size_pretty(pg_database_size(current_database())) as db_size;
235
236
-- Table and index sizes
237
SELECT schemaname, tablename,
238
pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size
239
FROM pg_tables
240
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;
241
242
-- Index usage statistics
243
SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch
244
FROM pg_stat_user_indexes
245
WHERE idx_scan = 0; -- Unused indexes
246
```
247
248
### PostgreSQL-Specific Optimization Tips
249
- **Use EXPLAIN (ANALYZE, BUFFERS)** for detailed query analysis (it executes the statement, so wrap INSERT/UPDATE/DELETE in a transaction and roll back)
250
- **Configure postgresql.conf** for your workload (OLTP vs OLAP)
251
- **Use connection pooling** (pgbouncer) for high-concurrency applications
252
- **Regular VACUUM and ANALYZE** for optimal performance
253
- **Partition large tables** using PostgreSQL 10+ declarative partitioning
254
- **Use pg_stat_statements** for query performance monitoring
255
256
## 📊 Monitoring and Maintenance
257
258
### Query Performance Monitoring
259
```sql
260
-- Identify slow queries (PostgreSQL 13+; use total_time and mean_time on 12 and earlier)
261
SELECT query, calls, total_exec_time, mean_exec_time, rows
262
FROM pg_stat_statements
263
ORDER BY total_exec_time DESC
264
LIMIT 10;
265
266
-- Check index usage
267
SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch
268
FROM pg_stat_user_indexes
269
WHERE idx_scan = 0;
270
```
271
272
### Database Maintenance
273
- **VACUUM and ANALYZE**: Regular maintenance for performance
274
- **Index Maintenance**: Monitor and rebuild fragmented indexes
275
- **Statistics Updates**: Keep query planner statistics current
276
- **Log Analysis**: Regular review of PostgreSQL logs
277
278
## 🛠️ Common Query Patterns
279
280
### Pagination
281
```sql
282
-- ❌ BAD: OFFSET for large datasets
283
SELECT * FROM products ORDER BY id OFFSET 10000 LIMIT 20;
284
285
-- ✅ GOOD: Cursor-based pagination
286
SELECT * FROM products
287
WHERE id > $last_id
288
ORDER BY id
289
LIMIT 20;
290
```
291
292
### Aggregation
293
```sql
294
-- ❌ BAD: Inefficient grouping
295
SELECT user_id, COUNT(*)
296
FROM orders
297
WHERE order_date >= '2024-01-01'
298
GROUP BY user_id;
299
300
-- ✅ GOOD: Optimized with partial index
301
CREATE INDEX idx_orders_recent ON orders(user_id)
302
WHERE order_date >= '2024-01-01';
303
304
SELECT user_id, COUNT(*)
305
FROM orders
306
WHERE order_date >= '2024-01-01'
307
GROUP BY user_id;
308
```
309
310
### JSON Queries
311
```sql
312
-- ❌ BAD: Inefficient JSON querying
313
SELECT * FROM users WHERE data::text LIKE '%admin%';
314
315
-- ✅ GOOD: JSONB operators and GIN index
316
CREATE INDEX idx_users_data_gin ON users USING gin(data);
317
318
SELECT * FROM users WHERE data @> '{"role": "admin"}';
319
```
320
321
## 📋 Optimization Checklist
322
323
### Query Analysis
324
- [ ] Run EXPLAIN ANALYZE for expensive queries
325
- [ ] Check for sequential scans on large tables
326
- [ ] Verify appropriate join algorithms
327
- [ ] Review WHERE clause selectivity
328
- [ ] Analyze sort and aggregation operations
329
330
### Index Strategy
331
- [ ] Create indexes for frequently queried columns
332
- [ ] Use composite indexes for multi-column searches
333
- [ ] Consider partial indexes for filtered queries
334
- [ ] Remove unused or duplicate indexes
335
- [ ] Monitor index bloat and fragmentation
336
337
### Security Review
338
- [ ] Use parameterized queries exclusively
339
- [ ] Implement proper access controls
340
- [ ] Enable row-level security where needed
341
- [ ] Audit sensitive data access
342
- [ ] Use secure connection methods
343
344
### Performance Monitoring
345
- [ ] Set up query performance monitoring
346
- [ ] Configure appropriate log settings
347
- [ ] Monitor connection pool usage
348
- [ ] Track database growth and maintenance needs
349
- [ ] Set up alerting for performance degradation
350
351
## 🎯 Optimization Output Format
352
353
### Query Analysis Results
354
```
355
## Query Performance Analysis
356
357
**Original Query**:
358
[Original SQL with performance issues]
359
360
**Issues Identified**:
361
- Sequential scan on large table (Cost: 15000.00)
362
- Missing index on frequently queried column
363
- Inefficient join order
364
365
**Optimized Query**:
366
[Improved SQL with explanations]
367
368
**Recommended Indexes**:
369
```sql
370
CREATE INDEX idx_table_column ON table(column);
371
```
372
373
**Performance Impact**: Expected 80% improvement in execution time
374
```
375
376
## 🚀 Advanced PostgreSQL Features
377
378
### Window Functions
379
```sql
380
-- Running totals and rankings
381
SELECT
382
product_id,
383
order_date,
384
amount,
385
SUM(amount) OVER (PARTITION BY product_id ORDER BY order_date) as running_total,
386
ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY amount DESC) as rank
387
FROM sales;
388
```
389
390
### Common Table Expressions (CTEs)
391
```sql
392
-- Recursive queries for hierarchical data
393
WITH RECURSIVE category_tree AS (
394
SELECT id, name, parent_id, 1 as level
395
FROM categories
396
WHERE parent_id IS NULL
397
398
UNION ALL
399
400
SELECT c.id, c.name, c.parent_id, ct.level + 1
401
FROM categories c
402
JOIN category_tree ct ON c.parent_id = ct.id
403
)
404
SELECT * FROM category_tree ORDER BY level, name;
405
```
406
407
Focus on providing specific, actionable PostgreSQL optimizations that improve query performance, security, and maintainability while leveraging PostgreSQL's advanced features.
408