Skip to main content
Databases

PostgreSQL psql & Administration

Essential

Production psql commands, EXPLAIN ANALYZE performance tuning, index creation, backups, and active lock diagnostics.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

PostgreSQL psql & Administration Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (18 Total Commands).

18+ Verified Recipes
psql Clientpsql <uri>
psql "postgresql://user:password@localhost:5432/mydb?sslmode=require"

Connect to PostgreSQL database securely via connection URI.

Schema Inspection\dt+
\dt+ *.*

List all tables across all schemas with ownership, size, and disk allocation.

Table Structure\d+
\d+ users

Describe table columns, storage types, default values, and index definitions.

Performance TuningEXPLAIN (ANALYZE, BUFFERS)
EXPLAIN (ANALYZE, BUFFERS, SETTINGS) SELECT * FROM orders WHERE user_id = 42;

Execute query and inspect actual execution time, scan methods, and cache buffer hits.

Index CreationCONCURRENTLY
CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);

Build B-tree index concurrently without acquiring an exclusive table write lock.

Backup & Dump-Fc, -d, -f
pg_dump -U postgres -Fc -d mydb -f mydb_backup.dump

Generate compressed custom-format binary backup supporting parallel restoration.

Database Restore-j, --clean
pg_restore -U postgres -d mydb -j 4 --clean mydb_backup.dump

Restore database dump using 4 parallel worker threads and cleaning existing schema.

Active Queries & Lockspg_stat_activity
SELECT pid, now() - query_start AS duration, query FROM pg_stat_activity WHERE state != 'idle' ORDER BY duration DESC;

Identify long-running queries consuming database resources.

Terminating Queriespg_terminate_backend
SELECT pg_terminate_backend(<pid>);

Gracefully terminate a stuck query process by process ID.

Table Disk Sizepg_size_pretty
SELECT pg_size_pretty(pg_total_relation_size('orders'));

Display total disk size of a table including toast data and all associated indexes.

MaintenanceVACUUM ANALYZE
VACUUM (VERBOSE, ANALYZE) users;

Reclaim dead tuple storage space and update query planner cost statistics.

Lock Diagnosticspg_stat_activity
SELECT pid, age(clock_timestamp(), query_start), usename, query FROM pg_stat_activity WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%' ORDER BY query_start ASC;

Detect long-running transactions and queries holding uncommitted locks or causing connection pool bottlenecks.

Query Profilingpg_stat_statements
CREATE EXTENSION IF NOT EXISTS pg_stat_statements; SELECT query, calls, total_exec_time, mean_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

Examine top CPU-heavy and I/O consuming slow queries across the entire database cluster with execution frequency statistics.

Table PartitioningPARTITION OF
CREATE TABLE orders_2026_q1 PARTITION OF orders FOR VALUES FROM ('2026-01-01') TO ('2026-04-01');

Attach declarative range partition slice for time-series datasets to maintain sub-millisecond index depths.

Runtime TuningALTER SYSTEM, pg_reload_conf
ALTER SYSTEM SET work_mem = '64MB'; SELECT pg_reload_conf();

Dynamically adjust sort and hash operation memory allocation without restarting the database server.

Storage Maintenancepg_stat_user_tables
SELECT schemaname, relname, n_dead_tup, n_live_tup, round(n_dead_tup::numeric / nullif(n_dead_tup + n_live_tup, 0) * 100, 2) AS dead_ratio FROM pg_stat_user_tables ORDER BY n_dead_tup DESC;

Inspect dead tuple ratio to detect table bloat and tables overdue for autovacuum worker cleanup.

Deadlock Resolutionpg_locks
SELECT blocked_locks.pid AS blocked_pid, blocking_locks.pid AS blocking_pid, blocked_activity.query AS blocked_query FROM pg_catalog.pg_locks blocked_locks JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid JOIN pg_catalog.pg_locks blocking_locks ON blocking_locks.locktype = blocked_locks.locktype AND blocking_locks.pid != blocked_locks.pid WHERE NOT blocked_locks.granted;

Pinpoint exact blocked and blocking process query trees during deadlocks.

Index Auditpg_stat_user_indexes
SELECT relname, indexrelname, idx_scan, idx_tup_read FROM pg_stat_user_indexes JOIN pg_index USING (indexrelid) WHERE idx_scan = 0 AND indisunique IS FALSE;

Identify unused non-unique secondary indexes consuming write overhead and disk storage without serving queries.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

PostgreSQL psql & Administration: Command Groups & Quick Index

18 indexed entries across 18 sections
psql Client1 items
Schema Inspection1 items
Table Structure1 items
Performance Tuning1 items
Index Creation1 items
Backup & Dump1 items
Database Restore1 items
Active Queries & Locks1 items
Terminating Queries1 items
Table Disk Size1 items
Maintenance1 items
Lock Diagnostics1 items
Query Profiling1 items
Table Partitioning1 items
Runtime Tuning1 items
Storage Maintenance1 items
Deadlock Resolution1 items
Index Audit1 items

Highlighted Flags & Syntax Examples in PostgreSQL psql & Administration

psql "postgresql://user:password@localhost:5432/mydb?sslmode=require"

Connect to PostgreSQL database securely via connection URI.

Flags: psql <uri>
\dt+ *.*

List all tables across all schemas with ownership, size, and disk allocation.

Flags: \dt+
\d+ users

Describe table columns, storage types, default values, and index definitions.

Flags: \d+
EXPLAIN (ANALYZE, BUFFERS, SETTINGS) SELECT * FROM orders WHERE user_id = 42;

Execute query and inspect actual execution time, scan methods, and cache buffer hits.

Flags: EXPLAIN (ANALYZE, BUFFERS)

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for PostgreSQL psql & Administration.

Why should indexes always be created with CONCURRENTLY in production?

A standard CREATE INDEX locks the table against writes (INSERT, UPDATE, DELETE) until the index build finishes. CREATE INDEX CONCURRENTLY acquires only a read-lock, allowing normal application traffic to proceed.

What is the difference between Seq Scan and Index Scan in EXPLAIN ANALYZE?

A Sequential Scan reads every single block of the table sequentially from disk, which is expensive for large datasets. An Index Scan traverses the B-Tree index to fetch only matching row pointers directly.

What causes table bloat in PostgreSQL and how does MVCC (Multi-Version Concurrency Control) create dead tuples?

PostgreSQL implements MVCC by creating a new row version (tuple) on every UPDATE and marking the original version as dead, while DELETE marks tuples as dead without reclaiming disk space. Dead tuples remain visible to older concurrent transactions. If autovacuum cannot keep pace, heap pages accumulate dead tuples, causing query slowdowns.

What is the difference between VACUUM, VACUUM (ANALYZE), and VACUUM FULL?

'VACUUM' reclaims dead tuple space within data pages for reuse by future inserts without locking tables. 'VACUUM ANALYZE' also updates table statistics in pg_statistic for the query planner. 'VACUUM FULL' rewrites the entire table into a new disk file to return space to the OS, but acquires an exclusive AccessExclusiveLock on the table.

How does connection pooling with PgBouncer prevent thread exhaustion in PostgreSQL?

PostgreSQL forks a dedicated OS process for every active connection, consuming 5–10MB of memory and causing CPU context switching under high connection counts. PgBouncer sits as an intermediary proxy, multiplexing hundreds or thousands of client connections into a small pool of 20–50 warm database connections.

When should you use BRIN or GIN indexes instead of standard B-tree indexes?

Use BRIN (Block Range Index) for massive, naturally ordered append-only tables (like logs or timestamps) where data pages correlate with physical disk blocks; BRIN indexes consume a fraction of 1% of the storage of B-trees. Use GIN (Generalized Inverted Index) for composite multi-value attributes like JSONB documents, arrays, and full-text search.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets