PostgreSQL Operations

SkillDatabases & data

PostgreSQL operations, optimization, and administration. Use for: schema design, index selection, query tuning with EXPLAIN ANALYZE, postgresql.conf configuration, backup and restore (pg_dump, pg_basebackup, WAL, PITR), vacuum and autovacuum tuning, connection pooling (pgBouncer, pgPool), replication (streaming, logical), partitioning, monitoring (pg_stat_statements, pg_stat_activity), JSONB operations, full-text search (tsvector, tsquery), row-level security (RLS), extensions (PostGIS, pg_trgm, timescaledb), GiST/GIN/BRIN indexes, materialized views, foreign data wrappers, LISTEN/NOTIFY.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the PostgreSQL Operations skill

What this skill tells your AI

The instructions your AI receives, as published by 0xdarkmatter/claude-mods in skills/postgres-ops/SKILL.md and read by ahel’s review.

Comprehensive PostgreSQL skill covering schema design through production operations.

Quick Connection

# Standard connection
psql "postgresql://user:pass@localhost:5432/dbname"

# With SSL
psql "postgresql://user:pass@host:5432/dbname?sslmode=require"

# Environment variables (libpq)
export PGHOST=localhost PGPORT=5432 PGDATABASE=mydb PGUSER=myuser PGPASSWORD=secret
psql

# Connection pooling (pgBouncer default)
psql "postgresql://user:pass@localhost:6432/dbname"
-- Check current connection
SELECT current_database(), current_user, inet_server_addr(), inet_server_port();

-- Active connections
SELECT count(*) FROM pg_stat_activity WHERE state = 'active';

Index Type Selection

What query pattern are you optimizing?
│
├─ Equality (WHERE col = val)
│  └─ B-tree (default, almost always right)
│
├─ Range (WHERE col > val, ORDER BY, BETWEEN)
│  └─ B-tree
│
├─ Array/JSONB containment (@>, ?, ?|, ?&)
│  └─ GIN
│
├─ Full-text search (@@)
│  └─ GIN with tsvector
│
├─ Geometric/range overlap (&&, <->)
│  └─ GiST
│
├─ Pattern matching (LIKE '%text%', similarity)
│  └─ GIN with pg_trgm (gin_trgm_ops)
│
├─ Large table, few distinct values, append-only
│  └─ BRIN (tiny index, good for timestamps)
│
└─ Exact equality only, no range/sort needed
   └─ Hash (rare - B-tree usually better)

Quick Index Reference

IndexBest ForSizeWrite Cost
B-treeEquality, range, sortMediumLow
GINArrays, JSONB, FTS, trigramsLargeHigh
GiSTGeometry, ranges, FTSMediumMedium
BRINCorrelated data (timestamps)TinyVery low
HashExact equality onlyMediumLow

Deep dive: Load ./references/indexing.md for composite, partial, expression, and covering index strategies.

EXPLAIN ANALYZE Workflow

-- Step 1: Run with ANALYZE and BUFFERS
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;

-- Step 2: Read bottom-up. Find the slowest node.
-- Step 3: Check estimates vs actuals
--   actual rows=10000, rows=100  -> bad estimate, run ANALYZE
-- Step 4: Look for these red flags:
Red FlagMeaningFix
Seq Scan on large tableNo usable indexAdd index matching WHERE/JOIN
actual rows >> estimated rowsStale statisticsANALYZE tablename
Nested Loop with high rowsO(n*m) joinCheck join conditions, add index
Sort with external mergework_mem too smallIncrease work_mem for session
Buffers: shared read >> hitCold cache or table too largeCheck shared_buffers, add covering index
Hash Batch > 1Hash join spilling to diskIncrease work_mem

Deep dive: Load ./references/query-tuning.md for plan node reference and optimization patterns.

Workload Profiles

SettingOLTPOLAPNotes
shared_buffers25% RAM25% RAMSame baseline
work_mem4-16 MB256 MB-1 GBOLAP needs big sorts
effective_cache_size75% RAM75% RAMPlanner hint
random_page_cost1.1 (SSD)1.1 (SSD)Lower for SSD
max_parallel_workers_per_gather24-8OLAP benefits more
checkpoint_completion_target0.90.9Spread checkpoint I/O
wal_buffers64 MB64 MB-1 for auto
maintenance_work_mem512 MB1-2 GBFor VACUUM, CREATE INDEX

Deep dive: Load ./references/config-tuning.md for full postgresql.conf walkthrough and extension setup.

Common Operations

Backup & Restore

# Logical backup (single database)
pg_dump -Fc dbname > backup.dump

# Restore
pg_restore -d dbname backup.dump

# Parallel backup (faster for large DBs)
pg_dump -Fc -j4 dbname > backup.dump

# Base backup for PITR
pg_basebackup -D /backup/base -Ft -Xs -P

Vacuum & Maintenance

-- Manual vacuum (reclaim space, update stats)
VACUUM (VERBOSE, ANALYZE) tablename;

-- Full vacuum (rewrites table, exclusive lock)
VACUUM FULL tablename;  -- CAUTION: locks table

-- Reindex without downtime
REINDEX INDEX CONCURRENTLY idx_name;

-- Update statistics only
ANALYZE tablename;

Monitor Key Metrics

-- Slow queries (requires pg_stat_statements)
SELECT query, calls, mean_exec_time, total_exec_time
FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10;

-- Table bloat indicator
SELECT schemaname, relname, n_dead_tup, n_live_tup,
       round(n_dead_tup::numeric / NULLIF(n_live_tup, 0) * 100, 1) AS dead_pct
FROM pg_stat_user_tables WHERE n_dead_tup > 1000
ORDER BY n_dead_tup DESC;

-- Lock contention
SELECT pid, relation::regclass, mode, granted, query
FROM pg_locks JOIN pg_stat_activity USING (pid)
WHERE NOT granted;

-- Cache hit ratio (should be > 99%)
SELECT sum(heap_blks_hit) / NULLIF(sum(heap_blks_hit) + sum(heap_blks_read), 0) AS ratio
FROM pg_statio_user_tables;

Deep dive: Load ./references/operations.md for WAL archiving, PITR, autovacuum tuning, connection pooling.

Data Types Quick Reference

TypeUse WhenExample
JSONBSemi-structured data, flexible schema'{"tags": ["a","b"]}'::jsonb
ARRAYFixed-type listsARRAY['a','b','c']
tsrangeTime periods, scheduling'[2024-01-01, 2024-12-31)'::tsrange
tsvectorFull-text searchto_tsvector('english', body)
uuidDistributed IDsgen_random_uuid()
inet/cidrIP addresses, networks'192.168.1.0/24'::cidr

Deep dive: Load ./references/schema-design.md for normalization, constraints, RLS, generated columns, table inheritance.

Gotchas & Anti-Patterns

MistakeWhy It's BadFix
SELECT * in productionWastes bandwidth, blocks covering index scansList columns explicitly
Function on indexed column (WHERE UPPER(email) = ...)Prevents index useExpression index: CREATE INDEX ... ON (UPPER(email))
NOT IN (subquery) with NULLsReturns no rows if subquery has NULLUse NOT EXISTS
Missing ANALYZE after bulk loadPlanner uses stale row estimatesRun ANALYZE tablename
VACUUM FULL in productionExclusive lock on entire tableRegular VACUUM + pg_repack
LIMIT without ORDER BYNon-deterministic resultsAlways pair with ORDER BY
Offset pagination on large tablesScans and discards rowsKeyset pagination: WHERE id > last_id
Too many indexesSlows writes, wastes spaceAudit with pg_stat_user_indexes
Single shared connection poolContention across servicesPer-service pools via pgBouncer
default_transaction_isolation = serializableExcessive serialization failuresKeep read committed, use explicit SERIALIZABLE where needed

Row-Level Security (RLS) Quick Start

-- Enable RLS on table
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

-- Policy: users see only their own rows
CREATE POLICY user_isolation ON documents
    USING (owner_id = current_setting('app.current_user_id')::int);

-- Policy: admins see everything
CREATE POLICY admin_access ON documents
    USING (current_setting('app.role') = 'admin');

-- Set context per request (from app layer)
SET app.current_user_id = '42';
SET app.role = 'user';

Full-Text Search Quick Start

-- Add search column
ALTER TABLE articles ADD COLUMN search_vector tsvector
    GENERATED ALWAYS AS (to_tsvector('english', title || ' ' || body)) STORED;

-- Index it
CREATE INDEX idx_articles_fts ON articles USING gin(search_vector);

-- Search with ranking
SELECT title, ts_rank(search_vector, query) AS rank
FROM articles, to_tsquery('english', 'database & optimization') AS query
WHERE search_vector @@ query
ORDER BY rank DESC;

LISTEN/NOTIFY

-- Publisher
NOTIFY order_events, '{"order_id": 123, "status": "shipped"}';

-- Subscriber (in psql or app)
LISTEN order_events;

-- Check for notifications (app code)
-- Python: conn.poll(); conn.notifies
-- Node: client.on('notification', callback)

Reference Files

Load these for deep-dive topics. Each is self-contained.

ReferenceWhen to Load
./references/schema-design.mdDesigning tables, choosing types, constraints, RLS policies, JSONB modeling
./references/indexing.mdChoosing index types, composite/partial/expression indexes, index maintenance
./references/query-tuning.mdReading EXPLAIN plans, pg_stat_statements, optimizing specific query patterns
./references/operations.mdBackup/restore, WAL/PITR, vacuum tuning, monitoring, connection pooling
./references/replication.mdStreaming/logical replication, failover, partitioning, FDW
./references/config-tuning.mdpostgresql.conf settings, OLTP/OLAP profiles, extension setup

See Also

  • sql-ops - Vendor-neutral SQL patterns (CTEs, window functions, JOINs)
  • sqlite-ops - SQLite-specific patterns and operations
  • python-database-ops - SQLAlchemy ORM and async database patterns

Signals

GitHub stars
36
Forks
5
Last commit
Aug 2026

ahel review

  • S4info
    community integration — published by 0xdarkmatter, not postgres

Automated review, not a security audit. Ruleset v1.

Advanced
Catalog kind
skill
Gateway key
postgres-ops
Source
github.com/0xdarkmatter/claude-mods