208 commands · 12 cheat sheets · SQL

Operations, Replication, and Storage master quick reference

Browse 208 commands from 12 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.

Operations, Replication, and Storage · 15 commands

PostgreSQL Backup, Restore, and Point-in-Time Recovery Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Plain SQL dumppg_dump --dbname=appdb --format=plain --file=appdb.sqlView examples
Custom archivepg_dump --dbname=appdb --format=custom --file=appdb.dumpView examples
Parallel directory dumppg_dump --dbname=appdb --format=directory --jobs=4 --file=appdb.dirView examples
Dump cluster globalspg_dumpall --globals-only --file=globals.sqlView examples
Dump definitions onlypg_dump --dbname=appdb --schema-only --file=schema.sqlView examples
Dump data onlypg_dump --dbname=appdb --data-only --format=custom --file=data.dumpView examples
Inspect archive contentspg_restore --list appdb.dumpView examples
Restore and create databasepg_restore --create --dbname=postgres appdb.dumpView examples
Restore in parallelpg_restore --dbname=restore_test --jobs=4 appdb.dumpView examples
Drop archived objects firstpg_restore --clean --if-exists --dbname=restore_test appdb.dumpView examples
Restore plain SQLpsql -- SET=ON_ERROR_STOP= ON --dbname=restore_test --file=appdb.sqlView examples
Take a physical base backuppg_basebackup --pgdata=/backup/base --format=plain --wal-method=stream --progressView examples
Verify backup manifestpg_verifybackup /backup/baseView examples
Set a recovery timerecovery_target_time = '2026-08-12 14:30:00+00'View examples
Pause at the recovery targetrecovery_target_action = 'pause'View examples

Operations, Replication, and Storage · 29 commands

PostgreSQL Connection Authentication and pg_hba.conf Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Require SCRAM for one application pathhostssl orders +orders_login 10.24.0.0/16 scram-sha-256View examples
Reject a specific source before a broad allowhost all all 10.24.9.18/32 rejectView examples
Reject non-TLS TCP connectionshostnossl all all 0.0.0.0/0 rejectView examples
Match a database named after the rolehostssl sameuser all 10.24.0.0/16 scram-sha-256View examples
Match members of a login rolehostssl orders +orders_login 10.24.0.0/16 scram-sha-256View examples
Match physical replication connectionshostssl replication replicator 10.24.40.12/32 scram-sha-256View examples
Include an ordered policy directoryinclude_dir "pg_hba.d"View examples
Include an optional local policyinclude_if_exists "pg_hba.local.conf"View examples
Locate the active HBA pathSHOW hba_file;View examples
Find parse errors in HBA filesSELECT file_name, line_number, error FROM pg_hba_file_rules WHERE error IS NOT NULL;View examples
Review normalized rule orderSELECT rule_number, type, database, user_name, address, auth_method FROM pg_hba_file_rules ORDER BY rule_number;View examples
Request a configuration reloadSELECT pg_reload_conf();View examples
Store newly set passwords as SCRAM verifiersALTER SYSTEM SET password_encryption = 'scram-sha-256'; SELECT pg_reload_conf();View examples
Reset a password without exposing it in SQL history\password orders_appView examples
Require SCRAM in the final HBA policyhostssl orders orders_app 10.24.0.0/16 scram-sha-256View examples
Require TLS, a client certificate, and SCRAMhostssl orders +orders_login 10.24.0.0/16 scram-sha-256 clientcert=verify-fullView examples
Authenticate with a client certificatehostssl orders +orders_login 10.24.0.0/16 cert map=client_certsView examples
Verify the server and require channel bindingsslmode=verify-full gssencmode=disable sslrootcert=/etc/postgresql/app-ca.crt channel_binding=require require_auth=scram-sha-256View examples
Authenticate a local socket user with peerlocal admin postgres peer map=local_adminsView examples
Map an OS account to a database rolelocal_admins db-operator postgresView examples
Use ident only on a tightly controlled networkhost admin db_operator 10.24.60.0/24 ident map=managed_hostsView examples
Use encrypted LDAP search and bindhostssl all +directory_login 10.24.0.0/16 ldap ldapserver=ldap.example.com ldaptls=1 ldapbasedn="dc=example,dc=com"View examples
Authenticate a Kerberos principal with GSSAPIhost all +staff 10.24.0.0/16 gss include_realm=1 krb_realm=EXAMPLE.COM map=corp_gssView examples
Require GSSAPI-encrypted transporthostgssenc all +staff 10.24.0.0/16 gss include_realm=1 krb_realm=EXAMPLE.COM map=corp_gssView examples
Scope a password-file entry tightlydb.example.com:5432:orders:orders_app:replace- WITH-managed-secretView examples
Restrict a Unix password filechmod 0600 /run/secrets/orders.pgpassView examples
Connect through a named service profilepsql service=orders-prodView examples
Verify the current authenticated sessionSELECT current_user, current_database(), inet_client_addr(), ssl FROM pg_stat_ssl JOIN pg_stat_activity USING (pid) WHERE pid = pg_backend_pid();View examples
Label canary connection attemptspsql 'service=orders-canary application_name=hba-rollout-canary'View examples

Operations, Replication, and Storage · 17 commands

PostgreSQL Database Configuration and Session Settings Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Show one effective valueSHOW statement_timeout;View examples
Read a setting safelySELECT current_setting('app.request_id', true);View examples
Inspect source and contextSELECT name, setting, unit, context, source, pending_restart FROM pg_settings WHERE name = 'shared_buffers';View examples
Set for this sessionSET SESSION statement_timeout = '30s';View examples
Set for one transactionSET LOCAL lock_timeout = '2s';View examples
Set through a functionSELECT set_config('app.request_id', 'req-9f2a', true);View examples
Reset one overrideRESET statement_timeout;View examples
Set a database defaultALTER DATABASE appdb SET statement_timeout = '60s';View examples
Set a role defaultALTER ROLE report_reader SET default_transaction_read_only = ON;View examples
Set a role-database defaultALTER ROLE report_reader IN DATABASE appdb SET statement_timeout = '15s';View examples
Write a cluster overrideALTER SYSTEM SET log_min_duration_statement = '1s';View examples
Reload configurationSELECT pg_reload_conf();View examples
Validate file entriesSELECT sourcefile, sourceline, name, setting, error FROM pg_file_settings WHERE error IS NOT NULL OR NOT applied;View examples
Find pending restartsSELECT name, setting, sourcefile FROM pg_settings WHERE pending_restart ORDER BY name;View examples
Delegate one settingGRANT SET ON PARAMETER statement_timeout TO app_operator;View examples
Use a trusted search pathSET LOCAL search_path = pg_catalog, app;View examples
Inspect capacity settingsSELECT name, setting, unit, source FROM pg_settings WHERE name IN ('work_mem', 'max_connections', 'max_wal_senders');View examples

Operations, Replication, and Storage · 14 commands

PostgreSQL LISTEN, NOTIFY, and Event Messaging Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Listen on a channelLISTEN order_events;View examples
Stop one listenerUNLISTEN order_events;View examples
Stop all listenersUNLISTEN *;View examples
Send a literal payloadNOTIFY order_events, 'order:8421';View examples
Send a dynamic payloadSELECT pg_notify('order_events', json_build_object('id', 8421)::text);View examples
Notify from a triggerCREATE TRIGGER orders_notify AFTER INSERT ON app.orders FOR EACH ROW EXECUTE FUNCTION app.notify_order();View examples
Persist an outbox eventINSERT INTO app.event_outbox (topic, aggregate_id, payload) VALUES ('order.created', 8421, '{"version":1}'::jsonb);View examples
Claim pending eventsSELECT event_id FROM app.event_outbox WHERE published_at IS NULL ORDER BY event_id FOR UPDATE SKIP LOCKED LIMIT 100;View examples
Identify this backendSELECT pg_backend_pid();View examples
List active registrationsSELECT * FROM pg_listening_channels();View examples
Measure queue occupancySELECT pg_notification_queue_usage();View examples
Inspect queue capacitySHOW max_notify_queue_pages;View examples
Find old listener transactionsSELECT pid, xact_start, state FROM pg_stat_activity WHERE backend_type = 'client backend' AND xact_start IS NOT NULL ORDER BY xact_start;View examples
Version an event hintSELECT pg_notify('order_events', json_build_object('v', 1, 'event_id', 9001)::text);View examples

Operations, Replication, and Storage · 16 commands

PostgreSQL Logical Replication Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Enable logical WALALTER SYSTEM SET wal_level = 'logical';View examples
Inspect worker capacitySHOW max_replication_slots; SHOW max_wal_senders; SHOW max_logical_replication_workers;View examples
Publish explicit tablesCREATE PUBLICATION app_pub FOR TABLE app.customers, app.orders;View examples
Restrict operationsCREATE PUBLICATION audit_pub FOR TABLE app.audit_log WITH (publish = 'insert');View examples
Filter published rowsCREATE PUBLICATION eu_pub FOR TABLE app.accounts WHERE (region = 'EU');View examples
Publish selected columnsCREATE PUBLICATION profile_pub FOR TABLE app.profiles (id, display_name, updated_at);View examples
Choose replica identity indexALTER TABLE app.events REPLICA IDENTITY USING INDEX events_replica_key;View examples
Use full-row identityALTER TABLE app.legacy_rows REPLICA IDENTITY FULL;View examples
Create subscriptionCREATE SUBSCRIPTION app_sub CONNECTION :'publisher_conninfo' PUBLICATION app_pub;View examples
Create disabled subscriptionCREATE SUBSCRIPTION app_sub CONNECTION 'host=publisher dbname=app user=logical_sub' PUBLICATION app_pub WITH (connect=false);View examples
Refresh table membershipALTER SUBSCRIPTION app_sub REFRESH PUBLICATION WITH (copy_data = true);View examples
Stop subscription workersALTER SUBSCRIPTION app_sub DISABLE;View examples
Keep table-owner executionALTER SUBSCRIPTION app_sub SET (run_as_owner = false, password_required = true);View examples
Inspect apply workersSELECT subname, worker_type, pid, received_lsn, latest_end_lsn FROM pg_stat_subscription;View examples
Measure retained WALSELECT slot_name, active, wal_status, pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS retained_bytes FROM pg_replication_slots;View examples
Enable failover slot handlingALTER SUBSCRIPTION app_sub SET (failover = true);View examples

Operations, Replication, and Storage · 15 commands

PostgreSQL Monitoring: Sessions, Waits, and Progress Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
List active sessionsSELECT pid, usename, application_name, state, query_start FROM pg_stat_activity WHERE state = 'active';View examples
Measure transaction ageclock_timestamp() - xact_start AS transaction_ageView examples
Find idle transactionsWHERE state = 'idle in transaction' ORDER BY xact_start NULLS LASTView examples
Inspect wait eventsSELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event IS NOT NULL;View examples
Find direct blockersSELECT pid, pg_blocking_pids(pid) AS blocking_pids FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;View examples
Bound lock waitingSET LOCAL lock_timeout = '2s';View examples
Rank total execution timeSELECT queryid, calls, total_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;View examples
Rank mean execution timeSELECT queryid, calls, mean_exec_time FROM pg_stat_statements WHERE calls >= 100 ORDER BY mean_exec_time DESC;View examples
Calculate cache hit ratioblks_hit::numeric / NULLIF(blks_hit + blks_read, 0)View examples
Inspect backend I/OSELECT backend_type, object, context, reads, read_time, writes, write_time FROM pg_stat_io;View examples
Monitor VACUUM progressSELECT pid, relid::regclass, phase, heap_blks_scanned, heap_blks_total FROM pg_stat_progress_vacuum;View examples
Monitor index creationSELECT pid, relid::regclass, phase, blocks_done, blocks_total FROM pg_stat_progress_create_index;View examples
Measure replay byte lagpg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_byte_lagView examples
Inspect replication slotsSELECT slot_name, slot_type, active, restart_lsn, wal_status FROM pg_replication_slots;View examples
Refresh cached statisticsSELECT pg_stat_clear_snapshot();View examples

Operations, Replication, and Storage · 14 commands

PostgreSQL postgres_fdw and Foreign Tables Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Enable postgres_fdwCREATE EXTENSION postgres_fdw;View examples
Define a remote serverCREATE SERVER warehouse_server FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'db.internal', dbname 'warehouse', sslmode 'verify-full');View examples
Grant server usageGRANT USAGE ON FOREIGN SERVER warehouse_server TO reporting_role;View examples
Map a local roleCREATE USER MAPPING FOR reporting_role SERVER warehouse_server OPTIONS (user 'warehouse_reader', password :'fdw_password');View examples
Import selected tablesIMPORT FOREIGN SCHEMA analytics LIMIT TO (daily_sales, customers) FROM SERVER warehouse_server INTO warehouse_fdw;View examples
Define a foreign tableCREATE FOREIGN TABLE warehouse_fdw.daily_sales (sale_date date, total numeric) SERVER warehouse_server OPTIONS (schema_name 'analytics');View examples
Inspect shipped SQLEXPLAIN (VERBOSE, COSTS) SELECT * FROM warehouse_fdw.daily_sales WHERE sale_date >= DATE '2026-08-01';View examples
Request remote estimatesALTER SERVER warehouse_server OPTIONS (ADD use_remote_estimate 'true');View examples
Collect local estimatesANALYZE warehouse_fdw.daily_sales;View examples
Tune rows per fetchALTER FOREIGN TABLE warehouse_fdw.daily_sales OPTIONS (ADD fetch_size '1000');View examples
Batch foreign insertsALTER FOREIGN TABLE warehouse_fdw.staging_sales OPTIONS (ADD batch_size '200');View examples
Insert into a foreign tableINSERT INTO warehouse_fdw.staging_sales (sale_id, amount) VALUES ($1, $2);View examples
List open FDW connectionsSELECT * FROM postgres_fdw_get_connections();View examples
Close an unused connectionSELECT postgres_fdw_disconnect('warehouse_server');View examples

Operations, Replication, and Storage · 19 commands

PostgreSQL psql CLI and Meta-Commands Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Connect with a servicepsql service=reportingView examples
Override database and rolepsql -d appdb -U app_readerView examples
Suppress startup filespsql -X -d appdbView examples
Stop after an errorpsql -X -v ON_ERROR_STOP=1 -f migration.sql appdbView examples
Wrap a file atomicallypsql -X -1 -v ON_ERROR_STOP=1 -f migration.sql appdbView examples
Execute one SQL commandpsql -X -d appdb -c 'SELECT current_timestamp;'View examples
Set a script variablepsql -v tenant=acme -f report.sql appdbView examples
Quote a literal variableSELECT :'tenant' AS tenant;View examples
Quote an identifierSELECT count(*) FROM :"table_name";View examples
List relations\dt app.*View examples
Describe a relation\d+ app.ordersView examples
Show the current connection\conninfoView examples
Enable expanded display\x autoView examples
Select CSV output\pset format csvView examples
Hide headings and row counts\t onView examples
Include relative to script\ir fragments/indexes.sqlView examples
Print the query buffer\pView examples
Capture one result rowSELECT current_user AS actor \gset session_View examples
Time subsequent commands\timing onView examples

Operations, Replication, and Storage · 16 commands

PostgreSQL Streaming Replication and Failover Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Inspect sender capacitySHOW wal_level; SHOW max_wal_senders; SHOW max_replication_slots;View examples
Create replication loginCREATE ROLE standby_rep LOGIN REPLICATION; \password standby_repView examples
Create physical slotSELECT * FROM pg_create_physical_replication_slot('standby_a');View examples
Seed a standbypg_basebackup -h primary.example -U standby_rep -D /pgdata/18 -R -X stream -S standby_a -C --progressView examples
Configure upstreamprimary_conninfo = 'host=primary.example user=standby_rep application_name=standby_a sslmode=verify-full'View examples
Use permanent slotprimary_slot_name = 'standby_a'View examples
Inspect WAL sendersSELECT application_name, state, sync_state, sent_lsn, flush_lsn, replay_lsn FROM pg_stat_replication;View examples
Measure replay byte lagSELECT pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes FROM pg_stat_replication;View examples
Check standby replaySELECT pg_is_in_recovery(), pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp();View examples
Require priority standbyssynchronous_standby_names = 'FIRST 1 (standby_a, standby_b)'View examples
Require standby quorumsynchronous_standby_names = 'ANY 2 (standby_a, standby_b, standby_c)'View examples
Wait for replaySET LOCAL synchronous_commit = 'remote_apply';View examples
Inspect recovery conflictsSELECT datname, confl_snapshot, confl_lock, confl_bufferpin, confl_deadlock FROM pg_stat_database_conflicts;View examples
Verify server roleSELECT pg_is_in_recovery();View examples
Promote an approved standbySELECT pg_promote(wait => true, wait_seconds => 60);View examples
Preview pg_rewindpg_rewind --target-pgdata=/pgdata/18 --source-server='host=new-primary dbname=postgres user=rewind' --dry-run --progressView examples

Operations, Replication, and Storage · 17 commands

PostgreSQL Tablespaces, Storage, and Fillfactor Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a tablespaceCREATE TABLESPACE fastspace LOCATION '/srv/postgresql/fastspace';View examples
List tablespacesSELECT spcname, pg_tablespace_location(oid) FROM pg_tablespace;View examples
Grant create privilegeGRANT CREATE ON TABLESPACE fastspace TO app_owner;View examples
Place a new tableCREATE TABLE app.events (id bigint, payload jsonb) TABLESPACE fastspace;View examples
Place a new indexCREATE INDEX events_id_idx ON app.events (id) TABLESPACE fastspace;View examples
Move a tableALTER TABLE app.events SET TABLESPACE fastspace;View examples
Set heap fillfactorALTER TABLE app.sessions SET (fillfactor = 80);View examples
Reset heap fillfactorALTER TABLE app.sessions RESET (fillfactor);View examples
Set index fillfactorALTER INDEX app.events_tenant_time_idx SET (fillfactor = 80);View examples
Repack an index concurrentlyREINDEX INDEX CONCURRENTLY app.events_tenant_time_idx;View examples
Prefer external storageALTER TABLE app.events ALTER COLUMN payload SET STORAGE EXTERNAL;View examples
Set TOAST autovacuum scaleALTER TABLE app.events SET (toast.autovacuum_vacuum_scale_factor = 0.05);View examples
Set a vacuum scale factorALTER TABLE app.job_queue SET (autovacuum_vacuum_scale_factor = 0.02);View examples
Reset table overridesALTER TABLE app.job_queue RESET (autovacuum_vacuum_scale_factor);View examples
Show a relation tablespaceSELECT reltablespace FROM pg_class WHERE oid = 'app.events'::regclass;View examples
Measure a tablespaceSELECT pg_size_pretty(pg_tablespace_size('fastspace'));View examples
Drop an empty tablespaceDROP TABLESPACE fastspace;View examples

Operations, Replication, and Storage · 18 commands

PostgreSQL VACUUM, Autovacuum, and Bloat Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Vacuum one tableVACUUM public.orders;View examples
Vacuum and refresh statisticsVACUUM (ANALYZE, VERBOSE) public.orders;View examples
Inspect table maintenance healthSELECT relname, n_live_tup, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC;View examples
Find stale planner statisticsSELECT relname, n_mod_since_analyze, last_autoanalyze FROM pg_stat_user_tables ORDER BY n_mod_since_analyze DESC;View examples
Monitor active vacuum workSELECT pid, relid::regclass, phase, heap_blks_scanned, heap_blks_total FROM pg_stat_progress_vacuum;View examples
Identify autovacuum sessionsSELECT pid, backend_type, query_start, wait_event_type, wait_event FROM pg_stat_activity WHERE backend_type = 'autovacuum worker';View examples
Inspect autovacuum settingsSELECT name, setting, unit FROM pg_settings WHERE name LIKE 'autovacuum%' ORDER BY name;View examples
Tune a high-churn tableALTER TABLE public.orders SET (autovacuum_vacuum_scale_factor = 0.01, autovacuum_vacuum_threshold = 5000);View examples
Inspect table overridesSELECT relname, reloptions FROM pg_class WHERE oid = 'public.orders'::regclass;View examples
Rank database XID ageSELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY xid_age DESC;View examples
Rank table XID ageSELECT oid::regclass, age(relfrozenxid) AS xid_age FROM pg_class WHERE relkind IN ('r','m') ORDER BY xid_age DESC;View examples
Find old transaction horizonsSELECT pid, xact_start, backend_xmin, age(backend_xmin) FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY age(backend_xmin) DESC;View examples
Find old prepared transactionsSELECT gid, prepared, owner, database, age(transaction) FROM pg_prepared_xacts ORDER BY age(transaction) DESC;View examples
Inspect replication slot horizonsSELECT slot_name, slot_type, active, xmin, catalog_xmin FROM pg_replication_slots ORDER BY slot_name;View examples
Measure HOT update useSELECT relname, n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables ORDER BY n_tup_upd DESC;View examples
Reserve heap page spaceCREATE TABLE account_state (account_id bigint PRIMARY KEY, status text NOT NULL) WITH (fillfactor = 80);View examples
Compare table and total sizeSELECT pg_relation_size('public.orders'), pg_total_relation_size('public.orders');View examples
Rank total relation sizesSELECT relid::regclass, pg_total_relation_size(relid) AS bytes FROM pg_stat_user_tables ORDER BY bytes DESC;View examples

Operations, Replication, and Storage · 18 commands

PostgreSQL WAL, Checkpoints, and Durability Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Check fsyncSHOW fsync;View examples
Check full-page writesSHOW full_page_writes;View examples
Inspect the sync methodSHOW wal_sync_method;View examples
Use durable local commitSET LOCAL synchronous_commit = on;View examples
Allow asynchronous commitSET LOCAL synchronous_commit = off;View examples
Wait for replaySET LOCAL synchronous_commit = remote_apply;View examples
Show checkpoint intervalSHOW checkpoint_timeout;View examples
Show WAL soft limitSHOW max_wal_size;View examples
Spread checkpoint writesALTER SYSTEM SET checkpoint_completion_target = 0.9;View examples
Inspect checkpoint countersSELECT * FROM pg_stat_checkpointer;View examples
Inspect WAL generationSELECT wal_records, wal_fpi, wal_bytes, wal_buffers_full FROM pg_stat_wal;View examples
Check archive statusSELECT archived_count, failed_count, last_failed_wal, stats_reset FROM pg_stat_archiver;View examples
Check replication slotsSELECT slot_name, active, restart_lsn, wal_status FROM pg_replication_slots;View examples
Request a WAL switchSELECT pg_switch_wal();View examples
Force a checkpointCHECKPOINT;View examples
Check checkpoint role membershipSELECT pg_has_role(current_user, 'pg_checkpoint', 'MEMBER');View examples
Read the current WAL LSNSELECT pg_current_wal_lsn();View examples
Inspect checksum stateSHOW data_checksums;View examples
CMDMEMO TERMINALREAD ONLY