PostgreSQL DBA Scripts

PostgreSQL DBA Scripts

Ready-to-use PostgreSQL 17 DBA scripts, grouped by topic. Click a script to open it, then press Copy (or click inside the code to select all of it and press Ctrl+C). Replace the example names (appdb, app_user, /pgdata/...) with your own, and test every script on a test server before you use it in production.

Read-only safe to run, only reads data   Changes something test first   Dangerous can lose data or stop service
Open allClose all

1. Installation & Initial Setup 8 scripts

OS checks, install, initdb, SELinux, firewall, first-time setup

β–Ά1.1Check the operating system before installingShellRead-only

Run as root. Shows OS version, memory, disk, CPU, SELinux state and the kernel settings that matter for PostgreSQL.

cat /etc/os-release | head -3
free -h
df -hT /pgdata /var/lib/pgsql 2>/dev/null
nproc
getenforce
sysctl vm.swappiness vm.overcommit_memory vm.nr_hugepages
cat /sys/kernel/mm/transparent_hugepage/enabled
ulimit -n

Note: Transparent Huge Pages should be "never" or "madvise" for PostgreSQL. A low open-files limit (ulimit -n) can cause "too many open files" errors.

β–Ά1.2Install PostgreSQL 17 from the PGDG repository (RHEL 9)ShellChanges something

Run as root. Adds the official repository, disables the built-in module, and installs server and contrib packages. Use EL-8 in the URL for RHEL 8.

dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf -qy module disable postgresql
dnf install -y postgresql17-server postgresql17-contrib
rpm -qa | grep postgresql17
β–Ά1.3Create directories and initialize a cluster in a custom locationShellChanges something

Run as root. Creates the data, log, archive and backup directories, points the service to the new data directory, runs initdb with checksums, and starts PostgreSQL.

mkdir -p /pgdata/pgsql-17/data /pglogs/pgsql-17/logs /pgarch/pgsql-17/arch /pgbackup
chown -R postgres:postgres /pgdata /pglogs /pgarch /pgbackup
chmod 700 /pgdata/pgsql-17/data

mkdir -p /etc/systemd/system/postgresql-17.service.d
cat > /etc/systemd/system/postgresql-17.service.d/override.conf <<'EOF'
[Service]
Environment=PGDATA=/pgdata/pgsql-17/data
EOF
systemctl daemon-reload

sudo -iu postgres /usr/pgsql-17/bin/initdb -D /pgdata/pgsql-17/data -E UTF8 --locale=en_US.UTF-8 --data-checksums
systemctl enable --now postgresql-17
systemctl status postgresql-17 --no-pager

Note: Encoding, locale and checksums are best decided at initdb time. Change the paths if your layout is different.

β–Ά1.4Set SELinux contexts for the custom directoriesShellChanges something

Run as root. Without the right context SELinux blocks PostgreSQL from using /pgdata, /pglogs and /pgarch, and the service fails to start.

dnf install -y policycoreutils-python-utils
semanage fcontext -a -t postgresql_db_t  "/pgdata(/.*)?"
semanage fcontext -a -t postgresql_log_t "/pglogs(/.*)?"
semanage fcontext -a -t postgresql_db_t  "/pgarch(/.*)?"
restorecon -Rv /pgdata /pglogs /pgarch

# If something is still denied, see what SELinux blocked
ausearch -m avc -ts recent | tail -20
β–Ά1.5Open port 5432 only for the application networkShellChanges something

Run as root. Allows PostgreSQL connections only from one subnet instead of the whole network.

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port protocol="tcp" port="5432" accept'
firewall-cmd --reload
firewall-cmd --list-rich-rules
β–Ά1.6Set the postgres password and allow network connectionsSQL (psql)Changes something

Run in psql as postgres. Sets a password, makes the server listen on the network, and shows the pg_hba.conf line to add. listen_addresses needs a restart.

ALTER USER postgres WITH PASSWORD 'ChangeMe_Strong_Password';
ALTER SYSTEM SET listen_addresses = '*';

-- Add this line to pg_hba.conf (before any reject rule), then reload:
--   host  all  all  192.168.1.0/24  scram-sha-256
-- Then restart PostgreSQL:  systemctl restart postgresql-17
SELECT pg_reload_conf();

Note: Do not use trust for network connections. Keep the pg_hba.conf rules as narrow as possible.

β–Ά1.7Set up the environment of the postgres OS userShellChanges something

Run as the postgres OS user. Puts the PostgreSQL 17 tools in the path and sets PGDATA so pg_ctl, psql and pg_basebackup work without long paths.

cat >> ~/.bash_profile <<'EOF'
export PGDATA=/pgdata/pgsql-17/data
export PGPORT=5432
export PATH=/usr/pgsql-17/bin:$PATH
alias pglog='tail -100f /pglogs/pgsql-17/logs/postgresql-$(date +%a).log'
EOF
source ~/.bash_profile
psql --version
β–Ά1.8Verify the installationSQL (psql)Read-only

Run in psql. Confirms the version, the data directory, the port and that the server is accepting connections.

SELECT version();
SHOW data_directory;
SHOW port;
SHOW data_checksums;
SHOW server_encoding;
SELECT pg_postmaster_start_time(), pg_is_in_recovery();
\conninfo
-- From the shell:  pg_isready -h 127.0.0.1 -p 5432

2. Configuration & Parameters 8 scripts

postgresql.conf, ALTER SYSTEM, reload or restart, logging

β–Ά2.1Show all settings changed from the defaultSQL (psql)Read-only

Run in psql. Lists every parameter that is not at its built-in default, and where the value comes from.

SELECT name, setting, unit, source, sourcefile, sourceline
FROM pg_settings
WHERE source NOT IN ('default', 'override')
ORDER BY name;
β–Ά2.2Find parameters waiting for a restartSQL (psql)Read-only

Run in psql. After changing a parameter, shows whether a restart is still needed to apply it.

SELECT name, setting, pending_restart
FROM pg_settings
WHERE pending_restart;

-- Which parameters can only change with a restart
SELECT name, setting FROM pg_settings WHERE context = 'postmaster' ORDER BY name;

Note: An empty first result means nothing is waiting. Reload (pg_reload_conf) is enough for parameters with context sighup or user.

β–Ά2.3Check the configuration files for errorsSQL (psql)Read-only

Run in psql. Shows lines in postgresql.conf or postgresql.auto.conf that were not applied or have a syntax error, before you reload.

SELECT sourcefile, sourceline, name, setting, applied, error
FROM pg_file_settings
WHERE NOT applied OR error IS NOT NULL
ORDER BY sourcefile, sourceline;
β–Ά2.4Change a parameter and reloadSQL (psql)Changes something

Run in psql as a superuser. ALTER SYSTEM writes to postgresql.auto.conf. Use RESET to go back to the default.

ALTER SYSTEM SET work_mem = '32MB';
ALTER SYSTEM SET log_min_duration_statement = '2s';
SELECT pg_reload_conf();
SHOW work_mem;

-- Remove a change
ALTER SYSTEM RESET work_mem;
SELECT pg_reload_conf();
β–Ά2.5Settings for one database or one roleSQL (psql)Changes something

Run in psql. Overrides a parameter only for a database or a user, for example a longer timeout for the reporting user.

ALTER DATABASE appdb SET work_mem = '64MB';
ALTER ROLE report_user SET statement_timeout = '10min';
ALTER ROLE app_user SET search_path = app, public;

-- See all overrides
SELECT coalesce(d.datname, 'ALL') AS database, coalesce(r.rolname, 'ALL') AS role, s.setconfig
FROM pg_db_role_setting s
LEFT JOIN pg_database d ON d.oid = s.setdatabase
LEFT JOIN pg_roles r ON r.oid = s.setrole;
β–Ά2.6Memory parameter starting values from the server RAMShellRead-only

Run in the shell. Prints starting values for shared_buffers and related parameters from the RAM of the server. They are starting points, not final answers.

#!/bin/bash
RAM_MB=$(awk '/MemTotal/ {printf "%d", $2/1024}' /proc/meminfo)
MWM=$((RAM_MB/16)); [ $MWM -gt 2048 ] && MWM=2048
echo "RAM                   : ${RAM_MB} MB"
echo "shared_buffers        = $((RAM_MB/4))MB"
echo "effective_cache_size  = $((RAM_MB*3/4))MB"
echo "maintenance_work_mem  = ${MWM}MB"
echo "work_mem              = start at 16MB-64MB, raise per session for big reports"
echo "random_page_cost      = 1.1   # on SSD / NVMe storage"

Note: Tune with evidence: change one parameter at a time and compare EXPLAIN (ANALYZE, BUFFERS) before and after.

β–Ά2.7Recommended logging settingsSQL (psql)Changes something

Run in psql as a superuser. A good logging baseline for troubleshooting. logging_collector needs a restart, the others only a reload.

ALTER SYSTEM SET logging_collector = on;                       -- restart needed
ALTER SYSTEM SET log_directory = '/pglogs/pgsql-17/logs';
ALTER SYSTEM SET log_filename = 'postgresql-%a.log';
ALTER SYSTEM SET log_truncate_on_rotation = on;
ALTER SYSTEM SET log_rotation_age = '1d';
ALTER SYSTEM SET log_line_prefix = '%m [%p] %q%u@%d ';
ALTER SYSTEM SET log_min_duration_statement = '2s';
ALTER SYSTEM SET log_checkpoints = on;
ALTER SYSTEM SET log_connections = on;
ALTER SYSTEM SET log_disconnections = on;
ALTER SYSTEM SET log_lock_waits = on;
ALTER SYSTEM SET log_temp_files = '10MB';
ALTER SYSTEM SET log_autovacuum_min_duration = '1s';
SELECT pg_reload_conf();

Note: With log_filename postgresql-%a.log the files are named by weekday and are overwritten after a week, so the log never grows without limit.

β–Ά2.8Compare the settings of two serversShellRead-only

Run in the shell. Saves all settings of each server to a file and shows the differences. Useful after a migration or to check a standby against the primary.

psql -h 192.168.1.10 -U postgres -At -c "SELECT name || ' = ' || setting FROM pg_settings ORDER BY name" > /tmp/primary.txt
psql -h 192.168.1.11 -U postgres -At -c "SELECT name || ' = ' || setting FROM pg_settings ORDER BY name" > /tmp/standby.txt
diff /tmp/primary.txt /tmp/standby.txt

3. Architecture & Server Health 8 scripts

processes, memory, WAL, checkpoints, cache hit ratio

β–Ά3.1Server version, start time and data directorySQL (psql)Read-only

Run in psql. The first things to check when you connect to an unknown server.

SELECT version();
SELECT pg_postmaster_start_time() AS started, now() - pg_postmaster_start_time() AS uptime;
SELECT pg_is_in_recovery() AS is_standby;
SHOW data_directory;
SHOW config_file;
SHOW hba_file;
β–Ά3.2List the PostgreSQL processesShellRead-only

Run in the shell. Shows the postmaster and its background processes, and the same from inside the database.

ps -ef | grep '[p]ostgres:' | head -30
ps -o pid,ppid,rss,cmd -C postgres | head -5

# From SQL: sessions and background workers by type
psql -c "SELECT backend_type, count(*) FROM pg_stat_activity GROUP BY backend_type ORDER BY count DESC"
β–Ά3.3Cache hit ratio per databaseSQL (psql)Read-only

Run in psql. Percentage of block requests served from shared buffers. About 99% or more is normal for OLTP.

SELECT datname, blks_hit, blks_read,
       round(100.0 * blks_hit / NULLIF(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database
WHERE datname IS NOT NULL
ORDER BY blks_read DESC;

Note: A low ratio on a big reporting database that scans huge tables can be normal. Do not judge the server by this number alone.

β–Ά3.4See which tables are cached in shared buffersSQL (psql)Changes something

Run in psql inside the database. Needs the pg_buffercache extension (from the contrib package).

CREATE EXTENSION IF NOT EXISTS pg_buffercache;

SELECT c.relname, count(*) AS buffers,
       pg_size_pretty(count(*) * 8192) AS cached
FROM pg_buffercache b
JOIN pg_class c ON b.relfilenode = pg_relation_filenode(c.oid)
 AND b.reldatabase = (SELECT oid FROM pg_database WHERE datname = current_database())
GROUP BY c.relname
ORDER BY buffers DESC
LIMIT 15;
β–Ά3.5Checkpoint statistics (PostgreSQL 17)SQL (psql)Read-only

Run in psql. Timed checkpoints are healthy. Many requested checkpoints mean max_wal_size is too small for the write load.

SELECT num_timed, num_requested,
       round(write_time / 1000) AS write_sec, round(sync_time / 1000) AS sync_sec,
       buffers_written, stats_reset
FROM pg_stat_checkpointer;

SHOW checkpoint_timeout;
SHOW max_wal_size;

Note: In PostgreSQL 16 and older use pg_stat_bgwriter (checkpoints_timed, checkpoints_req). The columns moved to pg_stat_checkpointer in version 17.

β–Ά3.6WAL position, WAL volume and size of pg_walSQL (psql)Read-only

Run in psql as a superuser or pg_monitor member. Shows the current WAL file, how much WAL was generated, and how big pg_wal is.

SELECT pg_current_wal_lsn() AS current_lsn,
       pg_walfile_name(pg_current_wal_lsn()) AS current_wal_file;

SELECT wal_records, wal_fpi, pg_size_pretty(wal_bytes) AS wal_generated, stats_reset
FROM pg_stat_wal;

SELECT count(*) AS wal_files, pg_size_pretty(sum(size)) AS pg_wal_size
FROM pg_ls_waldir();
β–Ά3.7Check data checksums and corruption countersSQL (psql)Read-only

Run in psql. Confirms checksums are enabled and shows any checksum failure that PostgreSQL detected while reading data.

SHOW data_checksums;

SELECT datname, checksum_failures, checksum_last_failure
FROM pg_stat_database
WHERE checksum_failures > 0;

Note: Any row in the second result is serious. Check the log and the storage, restore from backup if needed. With the cluster stopped you can verify all files with: pg_checksums --check -D /pgdata/pgsql-17/data

β–Ά3.8Data directory layout and sizesShellRead-only

Run as the postgres OS user. Shows which part of the data directory uses the space.

cd /pgdata/pgsql-17/data
du -sh base global pg_wal pg_xact pg_tblspc 2>/dev/null
ls -l PG_VERSION postmaster.pid postgresql.conf postgresql.auto.conf pg_hba.conf
cat PG_VERSION
psql -At -c "SELECT oid || ' = ' || datname FROM pg_database ORDER BY oid"

4. Databases, Schemas & Tablespaces 9 scripts

sizes, create and drop, tablespaces, sequences

β–Ά4.1Size of every databaseSQL (psql)Read-only

Run in psql. Lists databases with their size, owner and encoding.

SELECT d.datname, pg_size_pretty(pg_database_size(d.datname)) AS size,
       pg_get_userbyid(d.datdba) AS owner, pg_encoding_to_char(d.encoding) AS encoding
FROM pg_database d
ORDER BY pg_database_size(d.datname) DESC;
β–Ά4.2Size of every schemaSQL (psql)Read-only

Run in psql inside the database. Total size of tables, indexes and TOAST data per schema.

SELECT schemaname,
       pg_size_pretty(sum(pg_total_relation_size(format('%I.%I', schemaname, tablename)::regclass))) AS size
FROM pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
GROUP BY schemaname
ORDER BY sum(pg_total_relation_size(format('%I.%I', schemaname, tablename)::regclass)) DESC;
β–Ά4.3Largest tables with index and TOAST sizesSQL (psql)Read-only

Run in psql inside the database. The 20 biggest tables, with the heap, index and total size and the estimated row count.

SELECT n.nspname AS schema, c.relname AS table_name,
       pg_size_pretty(pg_relation_size(c.oid))       AS heap,
       pg_size_pretty(pg_indexes_size(c.oid))        AS indexes,
       pg_size_pretty(pg_total_relation_size(c.oid)) AS total,
       c.reltuples::bigint                           AS est_rows
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'p', 'm')
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 20;

Note: pg_total_relation_size includes indexes and TOAST. pg_relation_size shows only the main table, so the two numbers differ.

β–Ά4.4Create a database with an owner and safe defaultsSQL (psql)Changes something

Run in psql as a superuser. Creates an owner role, the database, and closes the default PUBLIC access so only chosen users can connect.

CREATE ROLE app_owner NOLOGIN;
CREATE DATABASE appdb OWNER app_owner ENCODING 'UTF8' TEMPLATE template0;
REVOKE ALL ON DATABASE appdb FROM PUBLIC;
GRANT CONNECT ON DATABASE appdb TO app_owner;
\c appdb
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
β–Ά4.5Rename or drop a databaseSQL (psql)Dangerous

Run in psql as a superuser, connected to another database. WITH (FORCE) disconnects all sessions first. A dropped database cannot be recovered without a backup.

ALTER DATABASE appdb RENAME TO appdb_old;      -- no sessions may be connected to appdb

-- Disconnect everybody and drop (PostgreSQL 13 and later)
DROP DATABASE appdb_old WITH (FORCE);

Note: Take a backup before you drop anything, and double-check the database name.

β–Ά4.6Create a tablespace and move a table to itSQL (psql)Changes something

Run as root for the directory, then in psql. Moving a table takes an ACCESS EXCLUSIVE lock and copies the data, so do it in a quiet period.

-- Shell, as root:
--   mkdir -p /pgdata2/ts_fast && chown postgres:postgres /pgdata2/ts_fast && chmod 700 /pgdata2/ts_fast
CREATE TABLESPACE fast_ts LOCATION '/pgdata2/ts_fast';

ALTER TABLE orders SET TABLESPACE fast_ts;
ALTER INDEX idx_orders_customer SET TABLESPACE fast_ts;

SELECT spcname, pg_tablespace_location(oid), pg_size_pretty(pg_tablespace_size(spcname)) AS size
FROM pg_tablespace;

Note: A standby needs the same directory path. Tablespaces are outside PGDATA, so include them in your backup.

β–Ά4.7Tables without a primary keySQL (psql)Read-only

Run in psql inside the database. Tables without a primary key are a problem for logical replication, for tools like pg_repack and for data quality.

SELECT n.nspname AS schema, c.relname AS table_name
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
  AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary)
ORDER BY 1, 2;
β–Ά4.8Sequences close to their maximum valueSQL (psql)Read-only

Run in psql inside the database. An integer sequence that reaches its maximum makes inserts fail. Check the ones above 70%.

SELECT schemaname, sequencename, data_type, last_value, max_value,
       round(100.0 * last_value / max_value, 2) AS pct_used
FROM pg_sequences
WHERE last_value IS NOT NULL
ORDER BY pct_used DESC
LIMIT 20;

Note: For a serial (integer) column near 2 billion, plan to change the column and sequence to bigint.

β–Ά4.9Copy a database inside the serverSQL (psql)Changes something

Run in psql as a superuser. Clones a database with all its data. No session may be connected to the source database while it runs.

CREATE DATABASE appdb_copy TEMPLATE appdb OWNER app_owner;
SELECT datname, pg_size_pretty(pg_database_size(datname)) FROM pg_database WHERE datname LIKE 'appdb%';

5. Users, Roles & Privileges 10 scripts

create users, audit privileges, pg_hba.conf, passwords, drop roles

β–Ά5.1List roles with attributes and group membershipSQL (psql)Read-only

Run in psql. All login and group roles, their main attributes, expiry date and which groups they belong to.

SELECT r.rolname, r.rolsuper, r.rolcreatedb, r.rolcreaterole, r.rolcanlogin,
       r.rolreplication, r.rolconnlimit, r.rolvaliduntil,
       ARRAY(SELECT b.rolname FROM pg_auth_members m
             JOIN pg_roles b ON b.oid = m.roleid WHERE m.member = r.oid) AS member_of
FROM pg_roles r
WHERE r.rolname !~ '^pg_'
ORDER BY r.rolname;
β–Ά5.2Create a read-only user through a group roleSQL (psql)Changes something

Run in psql as a superuser. A group role holds the privileges and users become members. Future tables are covered by default privileges.

CREATE ROLE app_read NOLOGIN;
GRANT CONNECT ON DATABASE appdb TO app_read;
\c appdb
GRANT USAGE ON SCHEMA public TO app_read;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO app_read;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public GRANT SELECT ON TABLES TO app_read;

CREATE USER report_user WITH PASSWORD 'ChangeMe_Strong_Password' CONNECTION LIMIT 10;
GRANT app_read TO report_user;

Note: ALTER DEFAULT PRIVILEGES applies only to tables created by the role named in FOR ROLE. Use the role that creates your tables.

β–Ά5.3Create an application user with read and write accessSQL (psql)Changes something

Run in psql as a superuser. Same pattern as the read-only user, with write access and a timeout for the application.

CREATE ROLE app_write NOLOGIN;
GRANT CONNECT ON DATABASE appdb TO app_write;
\c appdb
GRANT USAGE ON SCHEMA public TO app_write;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_write;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_write;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_write;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO app_write;

CREATE USER app_user WITH PASSWORD 'ChangeMe_Strong_Password';
GRANT app_write TO app_user;
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '10min';
β–Ά5.4Audit what a user can accessSQL (psql)Read-only

Run in psql inside the database. Shows the table privileges of one role, and quick yes/no checks for specific objects.

SELECT table_schema, table_name, privilege_type
FROM information_schema.role_table_grants
WHERE grantee = 'app_user'
ORDER BY 1, 2, 3;

SELECT has_database_privilege('app_user', 'appdb', 'CONNECT') AS can_connect,
       has_schema_privilege('app_user', 'public', 'USAGE')    AS schema_usage,
       has_table_privilege('app_user', 'public.orders', 'SELECT') AS select_orders;

Note: Privileges inherited from group roles are not shown in role_table_grants. The has_*_privilege functions include them.

β–Ά5.5Show the active pg_hba.conf rules and errorsSQL (psql)Read-only

Run in psql. Shows the rules in the order they are checked. Always check for errors before you reload after an edit.

SELECT line_number, type, database, user_name, address, auth_method, error
FROM pg_hba_file_rules
ORDER BY line_number;

-- Only lines with a problem
SELECT line_number, error FROM pg_hba_file_rules WHERE error IS NOT NULL;

SELECT pg_reload_conf();
β–Ά5.6Check password types and move users from md5 to SCRAMSQL (psql)Changes something

Run in psql as a superuser. Shows which users still have md5 passwords. The hash cannot be converted, so each user needs a new password.

SELECT rolname,
       CASE WHEN rolpassword LIKE 'SCRAM-SHA-256%' THEN 'scram'
            WHEN rolpassword LIKE 'md5%' THEN 'md5' ELSE 'none' END AS method
FROM pg_authid
WHERE rolcanlogin
ORDER BY method, rolname;

ALTER SYSTEM SET password_encryption = 'scram-sha-256';
SELECT pg_reload_conf();
ALTER USER app_user WITH PASSWORD 'New_Strong_Password';

Note: Reset all md5 passwords first, then change the md5 rules in pg_hba.conf to scram-sha-256.

β–Ά5.7Lock a user, set an expiry date, disconnect the sessionsSQL (psql)Changes something

Run in psql as a superuser. NOLOGIN does not end sessions that are already open, so terminate them too.

ALTER ROLE app_user NOLOGIN;
ALTER ROLE app_user VALID UNTIL '2027-03-31';
ALTER ROLE app_user CONNECTION LIMIT 20;

SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE usename = 'app_user';

-- Unlock
ALTER ROLE app_user LOGIN;
β–Ά5.8Drop a role that owns objectsSQL (psql)Dangerous

Run in psql as a superuser, in every database where the role owns objects. REASSIGN OWNED gives the objects to another role first. DROP OWNED without it deletes the objects.

-- Run in EACH database:
REASSIGN OWNED BY old_user TO new_owner;
DROP OWNED BY old_user;
-- Then once, in any database:
DROP ROLE old_user;

Note: Never run DROP OWNED BY before REASSIGN OWNED unless you really want to delete the objects of the role.

β–Ά5.9Roles with expired or soon-expiring passwordsSQL (psql)Read-only

Run in psql. Finds login roles whose password has expired or expires within 14 days.

SELECT rolname, rolvaliduntil,
       CASE WHEN rolvaliduntil < now() THEN 'EXPIRED' ELSE 'expires soon' END AS status
FROM pg_roles
WHERE rolcanlogin AND rolvaliduntil IS NOT NULL
  AND rolvaliduntil < now() + interval '14 days'
ORDER BY rolvaliduntil;
β–Ά5.10Objects owned by a roleSQL (psql)Read-only

Run in psql inside the database. Use it before dropping a role, to see what it owns.

SELECT n.nspname AS schema, c.relname AS object, c.relkind AS kind
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relowner = 'app_user'::regrole
  AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
ORDER BY 1, 2;

6. Security & Audit 9 scripts

superusers, insecure rules, SSL, RLS, pgaudit, failed logins

β–Ά6.1Find superusers and powerful rolesSQL (psql)Read-only

Run in psql. Lists roles that can bypass security or manage other roles. Keep this list as short as possible.

SELECT rolname, rolsuper, rolcreaterole, rolcreatedb, rolreplication, rolbypassrls, rolcanlogin
FROM pg_roles
WHERE (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls)
  AND rolname !~ '^pg_'
ORDER BY rolsuper DESC, rolname;
β–Ά6.2Find insecure pg_hba.conf rulesSQL (psql)Read-only

Run in psql. Shows trust rules, old md5 rules and rules open to every address.

SELECT line_number, type, database, user_name, address, auth_method
FROM pg_hba_file_rules
WHERE auth_method IN ('trust', 'md5', 'password')
   OR address = '0.0.0.0'
   OR address IS NULL AND type LIKE 'host%'
ORDER BY line_number;

Note: A trust rule on a network address lets anyone connect without a password. Replace it with scram-sha-256.

β–Ά6.3Which connections use SSLSQL (psql)Read-only

Run in psql as a superuser or pg_monitor member. Shows the encryption state and the TLS version of every client session.

SELECT a.pid, a.usename, a.datname, a.client_addr, s.ssl, s.version, s.cipher
FROM pg_stat_ssl s
JOIN pg_stat_activity a ON a.pid = s.pid
WHERE a.backend_type = 'client backend'
ORDER BY s.ssl, a.usename;
β–Ά6.4Create a self-signed SSL certificate and enable SSLShellChanges something

Run as the postgres OS user. For testing. In production use a certificate from your company CA. A reload is enough to apply ssl = on.

cd /pgdata/pgsql-17/data
openssl req -new -x509 -days 365 -nodes -text -out server.crt -keyout server.key -subj "/CN=pgdba01"
chmod 600 server.key

psql -c "ALTER SYSTEM SET ssl = on"
psql -c "ALTER SYSTEM SET ssl_min_protocol_version = 'TLSv1.2'"
psql -c "SELECT pg_reload_conf()"

# pg_hba.conf: encrypted connections only from the network
#   hostssl    appdb   app_user   192.168.1.0/24   scram-sha-256
#   hostnossl  all     all        0.0.0.0/0        reject

Note: The private key must be owned by postgres with mode 600, or PostgreSQL will not use it.

β–Ά6.5Check the privileges on the public schema and databasesSQL (psql)Read-only

Run in psql. Finds places where every user (PUBLIC) still has access, which is not wanted in most systems.

SELECT datname, datacl FROM pg_database WHERE datname NOT IN ('template0', 'template1');

SELECT nspname, nspacl FROM pg_namespace WHERE nspname = 'public';
SELECT has_schema_privilege('public', 'public', 'CREATE') AS public_can_create_in_public_schema;

Note: Since PostgreSQL 15 ordinary users cannot create objects in the public schema by default, but upgraded clusters may keep the old setting.

β–Ά6.6List row-level security policiesSQL (psql)Read-only

Run in psql inside the database. Shows which tables use row-level security and the policies on them.

SELECT c.relname, c.relrowsecurity AS rls_enabled, c.relforcerowsecurity AS rls_forced
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND c.relrowsecurity;

SELECT schemaname, tablename, policyname, cmd, roles, qual, with_check
FROM pg_policies
ORDER BY tablename, policyname;
β–Ά6.7Enable pgauditSQL (psql)Changes something

Install the pgaudit package for PostgreSQL 17 first. Needs a restart because it is a preloaded library. Logs DDL, role changes and data writes.

-- postgresql.conf (then restart PostgreSQL):
--   shared_preload_libraries = 'pgaudit'

CREATE EXTENSION pgaudit;
ALTER SYSTEM SET pgaudit.log = 'ddl, role, write';
SELECT pg_reload_conf();

-- Basic built-in logging that needs no extension
ALTER SYSTEM SET log_connections = on;
ALTER SYSTEM SET log_disconnections = on;
ALTER SYSTEM SET log_statement = 'ddl';
SELECT pg_reload_conf();

Note: Audit logs can grow very large and may contain sensitive data. Keep them on a separate disk and limit who can read them.

β–Ά6.8Failed logins from the logShellRead-only

Run as the postgres OS user. Counts failed password attempts and rejected connections in the server log, by user and database.

LOG=/pglogs/pgsql-17/logs
grep -h "FATAL" $LOG/*.log | grep -E "password authentication failed|no pg_hba.conf entry" | \
  sed -E 's/^[^ ]+ [^ ]+ [^ ]+ //' | sort | uniq -c | sort -nr | head -20

# Last 20 FATAL errors
grep -h "FATAL" $LOG/*.log | tail -20
β–Ά6.9SECURITY DEFINER functions without a fixed search_pathSQL (psql)Read-only

Run in psql inside the database. These functions run with the rights of their owner. Without a fixed search_path another user can hijack them.

SELECT n.nspname AS schema, p.proname AS function, pg_get_userbyid(p.proowner) AS owner, p.proconfig
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE p.prosecdef
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND NOT EXISTS (SELECT 1 FROM unnest(coalesce(p.proconfig, '{}')) c WHERE c LIKE 'search_path=%');

-- Fix one function
-- ALTER FUNCTION app.my_func(int) SET search_path = app, pg_temp;

7. Sessions, Locks & Blocking 9 scripts

activity, long queries, blockers, terminate, timeouts

β–Ά7.1Current activity overviewSQL (psql)Read-only

Run in psql. How many sessions are in each state, and the sessions that are running a query right now.

SELECT state, count(*) FROM pg_stat_activity WHERE backend_type = 'client backend' GROUP BY state ORDER BY count DESC;

SELECT pid, usename, datname, client_addr, now() - query_start AS running_for,
       wait_event_type, wait_event, left(query, 80) AS query
FROM pg_stat_activity
WHERE state = 'active' AND pid <> pg_backend_pid()
ORDER BY query_start;
β–Ά7.2Long-running queries and transactionsSQL (psql)Read-only

Run in psql. Queries running longer than 5 minutes, and transactions open longer than 10 minutes. Long transactions block vacuum and cause bloat.

SELECT pid, usename, datname, state, now() - query_start AS query_age, left(query, 100) AS query
FROM pg_stat_activity
WHERE state = 'active' AND now() - query_start > interval '5 minutes'
ORDER BY query_start;

SELECT pid, usename, datname, state, now() - xact_start AS xact_age, left(query, 100) AS last_query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL AND now() - xact_start > interval '10 minutes'
ORDER BY xact_start;
β–Ά7.3Sessions idle in transactionSQL (psql)Read-only

Run in psql. A session that opened a transaction and does nothing holds locks and keeps dead rows alive. Often an application bug.

SELECT pid, usename, datname, client_addr, now() - state_change AS idle_for, left(query, 100) AS last_query
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
ORDER BY state_change;

Note: Prevent it with idle_in_transaction_session_timeout (see the timeouts script below).

β–Ά7.4Blocked and blocking sessionsSQL (psql)Read-only

Run in psql. Shows who waits for whom. Find the blocking session at the end of the chain, then decide whether to wait or terminate it.

SELECT blocked.pid  AS blocked_pid,  blocked.usename AS blocked_user,
       now() - blocked.query_start AS waiting_for,
       left(blocked.query, 60) AS blocked_query,
       blocking.pid AS blocking_pid, blocking.usename AS blocking_user,
       blocking.state AS blocking_state, left(blocking.query, 60) AS blocking_query
FROM pg_stat_activity blocked
CROSS JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid)
JOIN pg_stat_activity blocking ON blocking.pid = b.pid
ORDER BY waiting_for DESC;

-- Root blockers: they block others but are not blocked themselves
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 80) AS query
FROM pg_stat_activity
WHERE pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity)
  AND cardinality(pg_blocking_pids(pid)) = 0;
β–Ά7.5Cancel or terminate sessionsSQL (psql)Dangerous

Run in psql as a superuser. Cancel stops only the running query. Terminate ends the whole session and rolls back its open transaction.

-- Stop the current query only
SELECT pg_cancel_backend(12345);

-- End one session
SELECT pg_terminate_backend(12345);

-- End all sessions idle in transaction for more than 10 minutes
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction' AND now() - state_change > interval '10 minutes';

-- End all sessions of a database (before DROP or RENAME)
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'appdb' AND pid <> pg_backend_pid();

Note: Terminating a session in the middle of a big transaction means a long rollback. Do not use it on autovacuum workers that run to prevent wraparound.

β–Ά7.6Locks held on a tableSQL (psql)Read-only

Run in psql. Shows the table-level locks and whether each one is granted or waiting.

SELECT l.pid, a.usename, l.relation::regclass AS table_name, l.mode, l.granted,
       now() - a.xact_start AS xact_age, left(a.query, 60) AS query
FROM pg_locks l
JOIN pg_stat_activity a ON a.pid = l.pid
WHERE l.relation IS NOT NULL
  AND l.relation::regclass::text NOT LIKE 'pg_%'
  AND l.pid <> pg_backend_pid()
ORDER BY l.granted, a.xact_start;
β–Ά7.7Connection usage compared with max_connectionsSQL (psql)Read-only

Run in psql. Shows how close the server is to its connection limit, and which user, database or application uses the connections.

SELECT count(*) AS connections, current_setting('max_connections')::int AS max_connections,
       round(100.0 * count(*) / current_setting('max_connections')::int, 1) AS pct_used
FROM pg_stat_activity;

SELECT usename, datname, application_name, count(*) AS connections
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2, 3
ORDER BY connections DESC
LIMIT 15;
β–Ά7.8Wait events summarySQL (psql)Read-only

Run in psql. Shows what active sessions are waiting for right now, such as disk I/O, locks or the client. Run it a few times during a slowdown.

SELECT wait_event_type, wait_event, count(*) AS sessions
FROM pg_stat_activity
WHERE state = 'active' AND backend_type = 'client backend'
GROUP BY 1, 2
ORDER BY sessions DESC;
β–Ά7.9Set timeouts for a role or databaseSQL (psql)Changes something

Run in psql as a superuser. Protects the server from runaway queries, forgotten transactions and long lock waits.

ALTER ROLE app_user SET statement_timeout = '60s';
ALTER ROLE app_user SET lock_timeout = '10s';
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '10min';

-- Server-wide default for forgotten transactions
ALTER SYSTEM SET idle_in_transaction_session_timeout = '15min';
SELECT pg_reload_conf();

Note: Use a longer statement_timeout for batch and reporting users than for the web application user.

8. Statistics & ANALYZE 8 scripts

stale statistics, estimates, targets, extended statistics

β–Ά8.1Tables with old or missing statisticsSQL (psql)Read-only

Run in psql inside the database. Shows tables that changed a lot since the last analyze, or were never analyzed.

SELECT schemaname, relname, n_live_tup, n_mod_since_analyze, last_analyze, last_autoanalyze
FROM pg_stat_user_tables
WHERE n_mod_since_analyze > 1000
   OR (last_analyze IS NULL AND last_autoanalyze IS NULL)
ORDER BY n_mod_since_analyze DESC
LIMIT 20;
β–Ά8.2Run ANALYZE for a table, a column or the whole databaseSQL (psql)Changes something

Run in psql, or use vacuumdb from the shell. ANALYZE takes only a light lock and does not block reads or writes.

ANALYZE VERBOSE orders;
ANALYZE orders (customer_id);
ANALYZE;

-- From the shell: all databases, 4 parallel jobs
-- vacuumdb --all --analyze-only --jobs=4
β–Ά8.3Compare estimated and actual rows in a planSQL (psql)Read-only

Run in psql. A big gap between estimated rows and actual rows means the statistics are wrong or too coarse.

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE status = 'PENDING';

-- Look at: rows=<estimate>  versus  actual rows=<real>
-- Estimate 50, actual 240000  ->  run ANALYZE, then raise the statistics target

Note: EXPLAIN ANALYZE runs the query. For INSERT, UPDATE or DELETE wrap it in BEGIN ... ROLLBACK.

β–Ά8.4Raise the statistics target for one columnSQL (psql)Changes something

Run in psql. More detail for a column with very uneven data. The change applies at the next ANALYZE.

ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500;
ANALYZE orders;

SELECT attname, attstattarget FROM pg_attribute
WHERE attrelid = 'public.orders'::regclass AND attname = 'customer_id';

-- Back to the default
ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS -1;
β–Ά8.5Extended statistics for related columnsSQL (psql)Changes something

Run in psql. Tells the planner that two columns are related, for example city and zip code, so row estimates become correct.

CREATE STATISTICS addr_stats (dependencies, ndistinct, mcv) ON city, zip_code FROM customers;
ANALYZE customers;

SELECT stxname, stxkeys, stxkind FROM pg_statistic_ext;
SELECT * FROM pg_stats_ext WHERE statistics_name = 'addr_stats';
β–Ά8.6Read the statistics of a columnSQL (psql)Read-only

Run in psql. Shows what the planner knows about a column: NULL fraction, distinct values, most common values and correlation.

SELECT attname, null_frac, n_distinct, most_common_vals, most_common_freqs, correlation
FROM pg_stats
WHERE schemaname = 'public' AND tablename = 'orders' AND attname = 'status';
β–Ά8.7Make auto-analyze run earlier on a large tableSQL (psql)Changes something

Run in psql. The default scale factor of 0.1 means 10 million changes on a 100 million row table before a new analyze. Lower it for large tables.

ALTER TABLE orders SET (autovacuum_analyze_scale_factor = 0.01, autovacuum_analyze_threshold = 500);

SELECT relname, reloptions FROM pg_class WHERE relname = 'orders';
β–Ά8.8Rebuild statistics after a restore or pg_upgradeShellChanges something

Run as the postgres OS user. Statistics are not carried over. The staged analyze gives usable statistics quickly so the application can start sooner.

vacuumdb --all --analyze-in-stages

# Or a complete analyze in one pass with parallel jobs
vacuumdb --all --analyze-only --jobs=4

9. VACUUM, Bloat & Wraparound 10 scripts

dead tuples, autovacuum tuning, blockers, wraparound, bloat

β–Ά9.1Dead tuples and last vacuum per tableSQL (psql)Read-only

Run in psql inside the database. Tables with the most dead rows, when they were last vacuumed, and how often autovacuum ran.

SELECT schemaname, relname, n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_vacuum, last_autovacuum, autovacuum_count
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 15;
β–Ά9.2Tables close to the autovacuum thresholdSQL (psql)Read-only

Run in psql inside the database. Compares dead tuples with the default trigger point (50 + 20% of rows). Tables far above it are not being vacuumed.

SELECT s.relname, s.n_dead_tup, round(50 + 0.2 * c.reltuples) AS default_threshold,
       s.last_autovacuum, s.autovacuum_count
FROM pg_stat_user_tables s
JOIN pg_class c ON c.oid = s.relid
WHERE s.n_dead_tup > 50 + 0.2 * c.reltuples
ORDER BY s.n_dead_tup DESC;

SHOW autovacuum;
SELECT relname, reloptions FROM pg_class WHERE reloptions IS NOT NULL;
β–Ά9.3Progress of a running vacuumSQL (psql)Read-only

Run in psql. Shows each running vacuum, its phase and how much of the table it has scanned.

SELECT pid, relid::regclass AS table_name, phase, heap_blks_total, heap_blks_scanned, heap_blks_vacuumed,
       round(100.0 * heap_blks_scanned / NULLIF(heap_blks_total, 0), 1) AS scanned_pct
FROM pg_stat_progress_vacuum;

SELECT pid, now() - xact_start AS runtime, query FROM pg_stat_activity WHERE query LIKE 'autovacuum:%';

Note: A query text with "(to prevent wraparound)" is an anti-wraparound vacuum. Do not cancel it.

β–Ά9.4Tune autovacuum for a large or busy tableSQL (psql)Changes something

Run in psql. Per-table settings, no restart needed. Lowering the scale factor is the most important change for big tables.

ALTER TABLE orders SET (
  autovacuum_vacuum_scale_factor  = 0.01,
  autovacuum_vacuum_threshold     = 1000,
  autovacuum_analyze_scale_factor = 0.005,
  autovacuum_vacuum_cost_limit    = 2000
);

SELECT relname, reloptions FROM pg_class WHERE relname = 'orders';

-- Go back to the global defaults
ALTER TABLE orders RESET (autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold,
                          autovacuum_analyze_scale_factor, autovacuum_vacuum_cost_limit);
β–Ά9.5What prevents vacuum from removing dead rowsSQL (psql)Read-only

Run in psql. Finds the oldest open transaction, forgotten prepared transactions, stuck replication slots and standbys that hold back cleanup.

-- Oldest transactions
SELECT pid, usename, state, now() - xact_start AS xact_age, backend_xmin
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC LIMIT 5;

-- Forgotten prepared transactions
SELECT gid, prepared, owner FROM pg_prepared_xacts;

-- Replication slots that do not advance
SELECT slot_name, slot_type, active, xmin, catalog_xmin FROM pg_replication_slots;

-- Standbys with hot_standby_feedback
SELECT application_name, backend_xmin FROM pg_stat_replication WHERE backend_xmin IS NOT NULL;

Note: This is the most common answer to "autovacuum is on but my table is still bloated".

β–Ά9.6Transaction ID age of databases and tablesSQL (psql)Read-only

Run in psql. Wraparound protection forces a vacuum at 200 million (autovacuum_freeze_max_age). Anything above 1 billion needs attention at once.

SELECT datname, age(datfrozenxid) AS xid_age,
       round(100.0 * age(datfrozenxid) / 2000000000, 1) AS pct_of_limit
FROM pg_database
ORDER BY xid_age DESC;

SELECT c.oid::regclass AS table_name, age(c.relfrozenxid) AS xid_age
FROM pg_class c
WHERE c.relkind IN ('r', 'm', 't')
ORDER BY xid_age DESC LIMIT 10;

SHOW autovacuum_freeze_max_age;
β–Ά9.7Measure bloat with pgstattupleSQL (psql)Changes something

Run in psql inside the database. pgstattuple reads the whole table, so on big tables use the approximate version.

CREATE EXTENSION IF NOT EXISTS pgstattuple;

SELECT table_len, tuple_percent, dead_tuple_percent, free_percent FROM pgstattuple('public.orders');

-- Faster estimate for big tables
SELECT * FROM pgstattuple_approx('public.orders');

-- Index bloat (B-tree)
SELECT * FROM pgstatindex('public.idx_orders_customer');
β–Ά9.8Manual vacuum commandsSQL (psql)Changes something

Run in psql. Plain VACUUM does not block normal work. Do not use VACUUM FULL on a busy table because it blocks everything.

VACUUM (VERBOSE, ANALYZE) orders;
VACUUM (PARALLEL 4, VERBOSE) orders;
VACUUM (FREEZE) orders;

-- Emergency, from the shell: freeze the oldest tables of all databases
-- vacuumdb --all --freeze --jobs=4
β–Ά9.9Shrink a bloated table online with pg_repackShellChanges something

Run as the postgres OS user. Rebuilds the table with only very short locks. Needs the pg_repack extension and a primary key or unique index on the table.

psql -d appdb -c "CREATE EXTENSION IF NOT EXISTS pg_repack"

# Dry run first
pg_repack -d appdb -t public.orders --dry-run
pg_repack -d appdb -t public.orders --jobs 2

# Only the indexes of a table
pg_repack -d appdb -t public.orders --only-indexes

Note: It needs free disk space for a second copy of the table. Run it in a quiet period.

β–Ά9.10Rebuild a bloated index without blocking writesSQL (psql)Changes something

Run in psql. REINDEX CONCURRENTLY builds a new index next to the old one and swaps them. Needs PostgreSQL 12 or later.

REINDEX INDEX CONCURRENTLY idx_orders_customer;
REINDEX TABLE CONCURRENTLY orders;

-- Indexes left invalid after a failure
SELECT indexrelid::regclass AS index_name, indrelid::regclass AS table_name
FROM pg_index WHERE NOT indisvalid;

10. Indexes & Query Tuning 10 scripts

pg_stat_statements, unused and duplicate indexes, plans

β–Ά10.1Enable pg_stat_statementsSQL (psql)Changes something

Run in psql as a superuser. The library must be preloaded, so a restart is required. If shared_preload_libraries already has entries, add to the list with a comma.

ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';
-- Restart:  systemctl restart postgresql-17
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Start a fresh measurement
SELECT pg_stat_statements_reset();
β–Ά10.2Top queries by total timeSQL (psql)Read-only

Run in psql. The queries that use the most total time. Fast queries that run millions of times appear here, unlike in the slow query log.

SELECT calls, round(total_exec_time::numeric, 1) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms,
       rows, left(query, 90) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;
β–Ά10.3Slowest queries on average, and queries that read the most from diskSQL (psql)Read-only

Run in psql. Two views of the problem: queries with a high average time, and queries that read many blocks from disk instead of cache.

SELECT calls, round(mean_exec_time::numeric, 1) AS mean_ms, round(max_exec_time::numeric, 1) AS max_ms, left(query, 90) AS query
FROM pg_stat_statements
WHERE calls > 50
ORDER BY mean_exec_time DESC
LIMIT 15;

SELECT calls, shared_blks_read, shared_blks_hit, temp_blks_written, left(query, 90) AS query
FROM pg_stat_statements
ORDER BY shared_blks_read DESC
LIMIT 15;
β–Ά10.4Unused indexesSQL (psql)Read-only

Run in psql inside the database. Indexes never used since the statistics were reset. Check the reset date first, and also look on the standby servers.

SELECT stats_reset FROM pg_stat_database WHERE datname = current_database();

SELECT s.schemaname, s.relname AS table_name, s.indexrelname AS index_name, s.idx_scan,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0 AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC;

Note: Never drop an index only because idx_scan is 0. Watch a full business cycle, including month-end jobs, and keep the CREATE INDEX statement.

β–Ά10.5Duplicate indexesSQL (psql)Read-only

Run in psql inside the database. Indexes on the same table with the same columns, operator class and condition. Keep one and drop the other.

SELECT indrelid::regclass AS table_name, array_agg(indexrelid::regclass) AS duplicate_indexes
FROM pg_index
GROUP BY indrelid, indkey, indclass, indpred::text, indexprs::text
HAVING count(*) > 1;

-- Drop without blocking writes
-- DROP INDEX CONCURRENTLY idx_old;
β–Ά10.6Foreign keys without an indexSQL (psql)Read-only

Run in psql inside the database. A foreign key column without an index makes deletes and updates on the parent table slow. This checks that the first column is indexed.

SELECT c.conrelid::regclass AS table_name, c.conname AS fk_name, pg_get_constraintdef(c.oid) AS definition
FROM pg_constraint c
WHERE c.contype = 'f'
  AND NOT EXISTS (SELECT 1 FROM pg_index i
                  WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1])
ORDER BY 1;
β–Ά10.7Tables with many sequential scansSQL (psql)Read-only

Run in psql inside the database. Large tables that are often read completely may need an index.

SELECT schemaname, relname, seq_scan, seq_tup_read, idx_scan, n_live_tup
FROM pg_stat_user_tables
WHERE n_live_tup > 10000 AND seq_scan > 100
ORDER BY seq_tup_read DESC
LIMIT 15;
β–Ά10.8Create an index without blocking the applicationSQL (psql)Changes something

Run in psql. CONCURRENTLY does not block writes but is slower and cannot run inside a transaction. A failure leaves an invalid index that you must drop.

CREATE INDEX CONCURRENTLY idx_orders_status ON orders (status);

-- Check the result
SELECT indexrelid::regclass, indisvalid FROM pg_index WHERE indrelid = 'orders'::regclass;

-- If it is invalid, drop it and try again
-- DROP INDEX CONCURRENTLY idx_orders_status;
β–Ά10.9Invalid indexesSQL (psql)Read-only

Run in psql inside the database. Invalid indexes are left behind by a failed CREATE INDEX CONCURRENTLY. They still slow down writes.

SELECT n.nspname, c.relname AS index_name, t.relname AS table_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE NOT i.indisvalid;
β–Ά10.10EXPLAIN template for a slow querySQL (psql)Read-only

Run in psql. The standard way to look at a plan. For data-changing statements wrap it in a transaction and roll it back.

EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT o.* FROM orders o WHERE o.customer_id = 42 ORDER BY o.created_at DESC LIMIT 20;

-- For INSERT / UPDATE / DELETE
BEGIN;
EXPLAIN (ANALYZE, BUFFERS) UPDATE orders SET status = 'DONE' WHERE id = 100;
ROLLBACK;

-- Test whether an index could be used (only in your own session)
SET enable_seqscan = off;
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
RESET enable_seqscan;

Note: Never turn off enable_* settings on the whole server. Use them only to understand a plan.

11. Backup & Recovery 11 scripts

pg_dump, base backup, WAL archiving, restore, PITR, verification

β–Ά11.1Daily logical backup of one database with retentionShellChanges something

Run as the postgres OS user, from cron. Dumps one database in custom format with the roles, writes a log, and removes backups older than 14 days.

#!/bin/bash
DB=appdb
DIR=/pgbackup/logical
KEEP_DAYS=14
TS=$(date +%F_%H%M)
mkdir -p $DIR

pg_dumpall --globals-only -f $DIR/globals_$TS.sql || exit 1
pg_dump -d $DB -Fc -f $DIR/${DB}_$TS.dump         || exit 1
pg_restore -l $DIR/${DB}_$TS.dump > /dev/null     || { echo "BACKUP UNREADABLE"; exit 1; }

find $DIR -type f -mtime +$KEEP_DAYS -delete
echo "$(date) backup of $DB ok: $(du -h $DIR/${DB}_$TS.dump | cut -f1)" >> /pglogs/backup.log

Note: Add to cron, for example: 30 1 * * * /home/postgres/backup_logical.sh

β–Ά11.2Backup all databases one by oneShellChanges something

Run as the postgres OS user. Loops over every database except the templates and writes one dump file for each.

#!/bin/bash
DIR=/pgbackup/logical/$(date +%F)
mkdir -p $DIR
pg_dumpall --globals-only -f $DIR/globals.sql
for DB in $(psql -At -c "SELECT datname FROM pg_database WHERE NOT datistemplate AND datname <> 'postgres'"); do
  pg_dump -d "$DB" -Fd -j 4 -f "$DIR/$DB" && echo "$DB ok" || echo "$DB FAILED"
done
β–Ά11.3Physical backup with pg_basebackup and retentionShellChanges something

Run as the postgres OS user, from cron. Takes a compressed online base backup including the WAL it needs, and keeps the last 14 days. Needs a REPLICATION role.

#!/bin/bash
BKP=/pgbackup/base_$(date +%F)
LOG=/pglogs/backup.log

pg_basebackup -h 127.0.0.1 -U replicator -D $BKP -Ft -z -X stream -c fast -P >> $LOG 2>&1
if [ $? -ne 0 ]; then echo "$(date) BASEBACKUP FAILED" >> $LOG; exit 1; fi

find /pgbackup -maxdepth 1 -name 'base_*' -mtime +14 -exec rm -rf {} \;
echo "$(date) base backup ok: $(du -sh $BKP | cut -f1)" >> $LOG

Note: Store the password in ~/.pgpass (mode 600) so the script needs no password prompt.

β–Ά11.4Enable WAL archivingSQL (psql)Changes something

Run in psql as a superuser. archive_mode needs a restart. The command copies each finished WAL file to the archive directory and must return 0 only on success.

ALTER SYSTEM SET archive_mode = 'on';
ALTER SYSTEM SET archive_command = 'test ! -f /pgarch/pgsql-17/arch/%f && cp %p /pgarch/pgsql-17/arch/%f';
ALTER SYSTEM SET archive_timeout = '5min';
-- Restart:  systemctl restart postgresql-17

SELECT pg_switch_wal();
SELECT archived_count, last_archived_wal, last_archived_time, failed_count, last_failed_wal, last_failed_time
FROM pg_stat_archiver;

Note: If archiving keeps failing, WAL piles up in pg_wal and the disk fills. Monitor failed_count.

β–Ά11.5Check that WAL archiving is healthyShellRead-only

Run as the postgres OS user. Shows archiver statistics, the newest archived file, how much WAL is waiting in pg_wal, and warns about failures.

psql -x -c "SELECT archived_count, last_archived_wal, last_archived_time, failed_count, last_failed_wal, last_failed_time FROM pg_stat_archiver"
ls -lt /pgarch/pgsql-17/arch | head -5
du -sh /pgarch/pgsql-17/arch
ls /pgdata/pgsql-17/data/pg_wal/archive_status/*.ready 2>/dev/null | wc -l   # files waiting to be archived

FAILS=$(psql -At -c "SELECT failed_count FROM pg_stat_archiver")
[ "$FAILS" -gt 0 ] && echo "WARNING: $FAILS failed archive attempts, check the log"
β–Ά11.6Restore a logical backupShellChanges something

Run as the postgres OS user. Restores roles first, creates the database, then loads the dump in parallel. Run ANALYZE afterwards.

psql -f /pgbackup/logical/globals_2026-11-20_0130.sql
psql -c "CREATE DATABASE appdb_restore"
pg_restore -d appdb_restore -j 4 -v /pgbackup/logical/appdb_2026-11-20_0130.dump
vacuumdb -d appdb_restore --analyze-only

# One table only
pg_restore -d appdb -t orders /pgbackup/logical/appdb_2026-11-20_0130.dump
# List the content of a backup
pg_restore -l /pgbackup/logical/appdb_2026-11-20_0130.dump | head
β–Ά11.7Point-in-time recovery from a base backup and archived WALShellDangerous

Run as root and postgres. Restores the base backup into an empty data directory and replays WAL up to a chosen time. The old data directory is moved aside, not deleted.

systemctl stop postgresql-17
mv /pgdata/pgsql-17/data /pgdata/pgsql-17/data_old

mkdir /pgdata/pgsql-17/data
chown postgres:postgres /pgdata/pgsql-17/data
chmod 700 /pgdata/pgsql-17/data
sudo -u postgres tar -xzf /pgbackup/base_2026-11-20/base.tar.gz -C /pgdata/pgsql-17/data
sudo -u postgres tar -xzf /pgbackup/base_2026-11-20/pg_wal.tar.gz -C /pgdata/pgsql-17/data/pg_wal

cat >> /pgdata/pgsql-17/data/postgresql.auto.conf <<'EOF'
restore_command = 'cp /pgarch/pgsql-17/arch/%f %p'
recovery_target_time = '2026-11-20 10:40:00'
recovery_target_action = 'pause'
EOF
sudo -u postgres touch /pgdata/pgsql-17/data/recovery.signal
systemctl start postgresql-17

# When the data is correct, end recovery and open the database for writes:
#   psql -c "SELECT pg_promote()"

Note: After recovery the server is on a new timeline. Take a fresh full backup. Remove the recovery settings from postgresql.auto.conf.

β–Ά11.8Verify a backupShellRead-only

Run as the postgres OS user. Three levels of checking: the manifest of a physical backup, the readability of a dump, and a real restore test.

# 1. Physical backup in plain format: check against its manifest
pg_verifybackup /pgbackup/base_plain

# 2. Logical backup: can it be read?
pg_restore -l /pgbackup/logical/appdb_2026-11-20_0130.dump > /dev/null && echo "dump readable"

# 3. Best: restore on a test server and run real queries
psql -d appdb_restore -c "SELECT count(*) FROM orders"

# 4. Check for corruption in the restored database
pg_amcheck -d appdb_restore

Note: A backup that was never restored is only a hope. Test a full restore every month.

β–Ά11.9Incremental backup (PostgreSQL 17)ShellChanges something

Run as the postgres OS user. Needs summarize_wal = on. An incremental backup copies only changed blocks. Combine the chain with pg_combinebackup before you start it.

psql -c "ALTER SYSTEM SET summarize_wal = on" -c "SELECT pg_reload_conf()"

# Full backup, then an incremental one based on its manifest
pg_basebackup -D /pgbackup/full  -Fp -X stream -c fast
pg_basebackup -D /pgbackup/incr1 -Fp -X stream -c fast --incremental=/pgbackup/full/backup_manifest

# Combine the chain into a normal backup
pg_combinebackup /pgbackup/full /pgbackup/incr1 -o /pgbackup/restore_ready

Note: An incremental backup cannot be started alone. Keep the full backup and every incremental in the chain.

β–Ά11.10Remove archived WAL that is no longer neededShellDangerous

Run as the postgres OS user. Finds the first WAL file needed by the oldest backup you keep, and removes only older files from the archive.

OLDEST=$(ls -d /pgbackup/base_* | head -1)
FIRST_WAL=$(tar -xzOf $OLDEST/base.tar.gz backup_label | sed -n 's/.*file \([0-9A-F]\{24\}\).*/\1/p' | head -1)
echo "oldest kept backup needs WAL from: $FIRST_WAL"

# Show what would be removed first
pg_archivecleanup -n /pgarch/pgsql-17/arch $FIRST_WAL
# Then do it
# pg_archivecleanup /pgarch/pgsql-17/arch $FIRST_WAL

Note: Never delete archived WAL by hand and never remove files newer than the oldest backup you keep.

β–Ά11.11pgBackRest daily commandsShellChanges something

Run as the postgres OS user. Full, differential and incremental backups, status, and a point-in-time restore with pgBackRest. The stanza is the name of your cluster in the configuration.

pgbackrest --stanza=main stanza-create
pgbackrest --stanza=main check

pgbackrest --stanza=main --type=full backup
pgbackrest --stanza=main --type=diff backup
pgbackrest --stanza=main --type=incr backup
pgbackrest --stanza=main info

# Restore to a point in time (PostgreSQL must be stopped)
pgbackrest --stanza=main --type=time "--target=2026-11-20 10:40:00" --target-action=promote --delta restore

12. Streaming Replication & High Availability 12 scripts

build a standby, lag, slots, switchover, pg_rewind, Patroni

β–Ά12.1Prepare the primary for streaming replicationSQL (psql)Changes something

Run in psql on the primary. Creates the replication user and sets the parameters. wal_level and max_wal_senders need a restart only if you change them.

CREATE ROLE replicator WITH LOGIN REPLICATION PASSWORD 'ChangeMe_Strong_Password';

ALTER SYSTEM SET wal_level = 'replica';
ALTER SYSTEM SET max_wal_senders = 10;
ALTER SYSTEM SET wal_keep_size = '2GB';
ALTER SYSTEM SET hot_standby = on;
SELECT pg_reload_conf();

-- pg_hba.conf on the primary (the database column must be the word "replication"):
--   host  replication  replicator  192.168.1.11/32  scram-sha-256
β–Ά12.2Build a standby with pg_basebackupShellDangerous

Run as root and postgres on the standby server. The data directory of the standby is emptied first. -R writes standby.signal and the connection settings.

systemctl stop postgresql-17
rm -rf /pgdata/pgsql-17/data/*

sudo -u postgres pg_basebackup -h 192.168.1.10 -U replicator -D /pgdata/pgsql-17/data \
     -Fp -X stream -R -C -S standby1_slot -P -v

systemctl start postgresql-17
sudo -u postgres psql -c "SELECT pg_is_in_recovery()"

Note: Add application_name=pgdba02 to primary_conninfo so the standby has a clear name in pg_stat_replication.

β–Ά12.3Replication status and lag on the primarySQL (psql)Read-only

Run in psql on the primary. One row per standby with its state and the lag as time and as bytes.

SELECT application_name, client_addr, state, sync_state,
       write_lag, flush_lag, replay_lag,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS replay_lag_bytes
FROM pg_stat_replication;

Note: state = streaming is healthy. No rows at all means no standby is connected.

β–Ά12.4Status and delay on the standbySQL (psql)Read-only

Run in psql on the standby. Confirms it is in recovery, connected to the primary, and how far behind it is.

SELECT pg_is_in_recovery();
SELECT status, written_lsn, flushed_lsn, sender_host, slot_name FROM pg_stat_wal_receiver;
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;
SELECT pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn();
β–Ά12.5Replication slots and the WAL they keepSQL (psql)Read-only

Run in psql on the primary. An inactive slot keeps WAL forever and can fill the disk.

SELECT slot_name, slot_type, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots
ORDER BY pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) DESC;

-- Limit the damage a stuck slot can do
ALTER SYSTEM SET max_slot_wal_keep_size = '50GB';
SELECT pg_reload_conf();

-- Remove a slot that is no longer needed
-- SELECT pg_drop_replication_slot('standby1_slot');
β–Ά12.6Configure synchronous replicationSQL (psql)Changes something

Run in psql on the primary. Commits wait for the first available standby in the list. With only one candidate, commits hang if that standby is down.

ALTER SYSTEM SET synchronous_standby_names = 'FIRST 1 (pgdba02, pgdba03)';
SELECT pg_reload_conf();

SELECT application_name, sync_state FROM pg_stat_replication;

-- Quorum style: any one of three
-- ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (pgdba02, pgdba03, pgdba04)';

-- Go back to asynchronous
-- ALTER SYSTEM RESET synchronous_standby_names;
β–Ά12.7Planned switchover and promotionShellDangerous

Run on the primary and the standby. A planned switchover stops the old primary cleanly so no data is lost. Stop the application before you start.

# 1. On the old primary
psql -c "CHECKPOINT"
systemctl stop postgresql-17

# 2. On the standby: confirm it has replayed everything, then promote
psql -c "SELECT pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn()"
sudo -u postgres /usr/pgsql-17/bin/pg_ctl promote -D /pgdata/pgsql-17/data
psql -c "SELECT pg_is_in_recovery()"        # must now be f

# 3. Rebuild the old primary as a standby of the new primary (see pg_rewind)
β–Ά12.8Rejoin the old primary with pg_rewindShellDangerous

Run as the postgres OS user on the old primary, after a switchover or failover. Needs wal_log_hints = on or data checksums. The server must be shut down cleanly first.

pg_rewind --target-pgdata=/pgdata/pgsql-17/data \
          --source-server='host=192.168.1.11 port=5432 user=postgres dbname=postgres' \
          --write-recovery-conf -P

systemctl start postgresql-17
psql -c "SELECT pg_is_in_recovery()"

Note: If pg_rewind cannot be used, rebuild the old primary with pg_basebackup.

β–Ά12.9Standby query conflictsSQL (psql)Read-only

Run in psql on the standby. Counts queries that were cancelled because of a conflict with replay, by reason.

SELECT datname, confl_snapshot, confl_lock, confl_bufferpin, confl_deadlock
FROM pg_stat_database_conflicts
WHERE datname NOT LIKE 'template%';

SHOW max_standby_streaming_delay;
SHOW hot_standby_feedback;
β–Ά12.10Patroni cluster commandsShellChanges something

Run as the postgres OS user on any Patroni node. Status, planned switchover, restart through Patroni, and configuration changes for the whole cluster.

patronictl -c /etc/patroni/patroni.yml list
patronictl -c /etc/patroni/patroni.yml topology
patronictl -c /etc/patroni/patroni.yml history

patronictl -c /etc/patroni/patroni.yml switchover
patronictl -c /etc/patroni/patroni.yml restart pgcluster pgdba02
patronictl -c /etc/patroni/patroni.yml reload pgcluster
patronictl -c /etc/patroni/patroni.yml reinit pgcluster pgdba02
patronictl -c /etc/patroni/patroni.yml edit-config

# Planned maintenance: stop automatic failover, then resume
patronictl -c /etc/patroni/patroni.yml pause
patronictl -c /etc/patroni/patroni.yml resume

Note: Do not restart PostgreSQL with systemctl on a Patroni node. Use patronictl so Patroni stays in control.

β–Ά12.11Find the primary through the Patroni REST APIShellRead-only

Run in the shell. The REST API answers 200 only on the primary (or only on a replica), which is what HAProxy health checks use.

curl -s -o /dev/null -w "primary:  %{http_code}\n" http://192.168.1.10:8008/primary
curl -s -o /dev/null -w "replica:  %{http_code}\n" http://192.168.1.11:8008/replica
curl -s http://192.168.1.10:8008/patroni | python3 -m json.tool | head -30
β–Ά12.12Replication lag alert scriptShellRead-only

Run as the postgres OS user, from cron on the primary. Prints a warning when a standby is missing or its replay lag is above the limit.

#!/bin/bash
LIMIT_MB=500
STANDBYS=$(psql -At -c "SELECT count(*) FROM pg_stat_replication WHERE state = 'streaming'")
[ "$STANDBYS" -lt 1 ] && echo "ALERT: no streaming standby connected"

psql -At -F'|' -c "SELECT application_name, round(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)/1024/1024) FROM pg_stat_replication" |
while IFS='|' read name lag; do
  [ "$lag" -gt "$LIMIT_MB" ] && echo "ALERT: $name is $lag MB behind"
done

13. Logical Replication 8 scripts

publication, subscription, monitoring, conflicts, sequences

β–Ά13.1Set up the publisherSQL (psql)Changes something

Run in psql on the publisher. wal_level = logical needs a restart. Every published table needs a primary key or a replica identity.

ALTER SYSTEM SET wal_level = 'logical';
-- Restart:  systemctl restart postgresql-17

CREATE ROLE logrepl WITH LOGIN REPLICATION PASSWORD 'ChangeMe_Strong_Password';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO logrepl;
-- pg_hba.conf:  host  appdb  logrepl  192.168.1.11/32  scram-sha-256

\c appdb
CREATE PUBLICATION app_pub FOR TABLE orders, customers;
-- or: CREATE PUBLICATION app_pub FOR ALL TABLES;
β–Ά13.2Set up the subscriberShellChanges something

Run on the subscriber. DDL is not replicated, so the tables must exist first. The subscription copies the existing data and then streams changes.

pg_dump -h 192.168.1.10 -U postgres -d appdb --schema-only -t orders -t customers | psql -d appdb

psql -d appdb <<'EOF'
CREATE SUBSCRIPTION app_sub
  CONNECTION 'host=192.168.1.10 port=5432 dbname=appdb user=logrepl password=ChangeMe_Strong_Password'
  PUBLICATION app_pub;
EOF
β–Ά13.3Monitor publications and subscriptionsSQL (psql)Read-only

Run in psql. The first group on the publisher, the second group on the subscriber. srsubstate r means ready.

-- On the PUBLISHER
SELECT * FROM pg_publication_tables;
SELECT application_name, state, sent_lsn, replay_lsn, replay_lag FROM pg_stat_replication;
SELECT slot_name, active, confirmed_flush_lsn,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots WHERE slot_type = 'logical';

-- On the SUBSCRIBER
SELECT subname, pid, received_lsn, latest_end_lsn, latest_end_time FROM pg_stat_subscription;
SELECT srrelid::regclass AS table_name, srsubstate FROM pg_subscription_rel;
β–Ά13.4Add or remove a table in a publicationSQL (psql)Changes something

Run in psql. Create the table on the subscriber first, then refresh the subscription.

-- Publisher
ALTER PUBLICATION app_pub ADD TABLE invoices;
ALTER PUBLICATION app_pub DROP TABLE customers;

-- Subscriber
ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION;
-- If the rows were already loaded:
-- ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION WITH (copy_data = false);
β–Ά13.5Fix a subscription stopped by a conflictSQL (psql)Dangerous

Run in psql on the subscriber. Read the error in the log first. Fixing the conflicting row is better than skipping the transaction, because SKIP loses that transaction permanently.

-- 1. See the error (shell):  grep -E "ERROR|logical replication" /pglogs/pgsql-17/logs/*.log | tail

-- 2a. Preferred: correct or delete the conflicting row on the subscriber. The subscription continues by itself.

-- 2b. Last resort: skip the failing transaction (LSN from the log message "finished at ...")
ALTER SUBSCRIPTION app_sub SKIP (lsn = '0/1A3F5C8');

-- Pause while you investigate, and stop automatically on errors
ALTER SUBSCRIPTION app_sub DISABLE;
ALTER SUBSCRIPTION app_sub SET (disable_on_error = true);
ALTER SUBSCRIPTION app_sub ENABLE;
β–Ά13.6Replica identity and tables without a primary keySQL (psql)Changes something

Run in psql on the publisher. UPDATE and DELETE on a published table fail without a primary key or replica identity.

-- Published tables without a primary key
SELECT pt.schemaname, pt.tablename
FROM pg_publication_tables pt
WHERE NOT EXISTS (
  SELECT 1 FROM pg_index i WHERE i.indrelid = format('%I.%I', pt.schemaname, pt.tablename)::regclass AND i.indisprimary);

-- Fix: use a unique index, or all columns (slow and large)
ALTER TABLE logs REPLICA IDENTITY USING INDEX logs_uniq_idx;
ALTER TABLE logs REPLICA IDENTITY FULL;
SELECT relname, relreplident FROM pg_class WHERE relname = 'logs';
β–Ά13.7Copy sequence values to the subscriberSQL (psql)Changes something

Sequences are not replicated. Run the first query on the publisher, then run its output on the subscriber, before a switchover.

-- On the publisher: generates one setval command per sequence
SELECT format('SELECT setval(%L, %s);', schemaname || '.' || sequencename, last_value)
FROM pg_sequences
WHERE last_value IS NOT NULL;

-- Copy the generated commands and run them on the subscriber.
β–Ά13.8Remove a subscription and its slotSQL (psql)Dangerous

Run in psql on the subscriber. Dropping the subscription also removes the slot on the publisher when it can be reached. If not, detach the slot first.

DROP SUBSCRIPTION app_sub;

-- If the publisher is not reachable:
ALTER SUBSCRIPTION app_sub DISABLE;
ALTER SUBSCRIPTION app_sub SET (slot_name = NONE);
DROP SUBSCRIPTION app_sub;

-- Then on the publisher, remove the slot yourself
SELECT pg_drop_replication_slot('app_sub');

Note: An inactive logical slot is a common reason for a full WAL disk. Always clean up slots of removed subscribers.

14. Partitioning & Large Tables 8 scripts

create, pruning, new and old partitions, batches

β–Ά14.1Create a range-partitioned table by monthSQL (psql)Changes something

Run in psql. The primary key must include the partition key. The default partition catches rows that fit no other partition.

CREATE TABLE sales (
  id        bigint GENERATED ALWAYS AS IDENTITY,
  sale_date date NOT NULL,
  amount    numeric(10,2),
  PRIMARY KEY (id, sale_date)
) PARTITION BY RANGE (sale_date);

CREATE TABLE sales_2026_11 PARTITION OF sales FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE sales_default PARTITION OF sales DEFAULT;
CREATE INDEX ON sales (sale_date);
β–Ά14.2Create the next 6 monthly partitions automaticallySQL (psql)Changes something

Run in psql, or schedule it. Creates the partitions for the coming months if they do not exist. Missing future partitions make inserts fail at the start of the month.

DO $$
DECLARE
  m date;
  i int;
BEGIN
  FOR i IN 0..5 LOOP
    m := (date_trunc('month', current_date) + (i || ' month')::interval)::date;
    EXECUTE format('CREATE TABLE IF NOT EXISTS sales_%s PARTITION OF sales FOR VALUES FROM (%L) TO (%L)',
                   to_char(m, 'YYYY_MM'), m, (m + interval '1 month')::date);
  END LOOP;
END $$;

Note: The pg_partman extension does the same with more options, and can also drop old partitions.

β–Ά14.3List partitions with size and rangeSQL (psql)Read-only

Run in psql. Shows every partition of a table with its range, estimated rows and size.

SELECT c.relname AS partition, pg_get_expr(c.relpartbound, c.oid) AS bounds,
       c.reltuples::bigint AS est_rows, pg_size_pretty(pg_total_relation_size(c.oid)) AS size
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = 'sales'::regclass
ORDER BY c.relname;
β–Ά14.4Check that partition pruning worksSQL (psql)Read-only

Run in psql. Only the matching partition should appear in the plan. A function on the partition key usually prevents pruning.

EXPLAIN SELECT * FROM sales WHERE sale_date = '2026-11-15';
-- Expect: Seq Scan on sales_2026_11 only

SHOW enable_partition_pruning;

-- Bad: hides the key from the planner
-- EXPLAIN SELECT * FROM sales WHERE date_trunc('month', sale_date) = '2026-11-01';
β–Ά14.5Attach a pre-loaded table as a new partitionSQL (psql)Changes something

Run in psql. Load the data in a separate table first. A matching CHECK constraint lets ATTACH skip the full table scan, so the lock is short. If the table has a default partition, PostgreSQL also scans the default partition to make sure no row belongs to the new range.

CREATE TABLE sales_2027_12 (LIKE sales INCLUDING ALL);
-- ... load the data with COPY ...
ALTER TABLE sales_2027_12 ADD CONSTRAINT chk_2027_12
  CHECK (sale_date >= '2027-12-01' AND sale_date < '2028-01-01');
ALTER TABLE sales ATTACH PARTITION sales_2027_12 FOR VALUES FROM ('2027-12-01') TO ('2028-01-01');
β–Ά14.6Remove an old partitionSQL (psql)Dangerous

Run in psql. Detaching and dropping is nearly instant and creates no bloat. Archive the data first if you may need it.

-- Optional archive first (shell):  pg_dump -d appdb -t sales_2025_10 -Fc -f /pgbackup/sales_2025_10.dump

ALTER TABLE sales DETACH PARTITION sales_2025_10;
DROP TABLE sales_2025_10;

-- Without a default partition you can detach with almost no blocking:
-- ALTER TABLE sales DETACH PARTITION sales_2025_10 CONCURRENTLY;

Note: DETACH ... CONCURRENTLY cannot run inside a transaction block and cannot be used when the table has a default partition. The plain DETACH takes a short, strong lock, so run it in a quiet moment.

β–Ά14.7Check that next month's partition existsSQL (psql)Read-only

Run in psql, or from a monitoring job. Shows the latest partition. Alert when it ends less than 30 days from now.

SELECT c.relname, pg_get_expr(c.relpartbound, c.oid) AS bounds
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = 'sales'::regclass
  AND pg_get_expr(c.relpartbound, c.oid) NOT LIKE '%DEFAULT%'
ORDER BY pg_get_expr(c.relpartbound, c.oid) DESC
LIMIT 1;
β–Ά14.8Delete or update a large table in batchesSQL (psql)Dangerous

Run in psql, not inside a transaction block. Deletes old rows 10000 at a time and commits each batch, so locks stay short and vacuum can keep up.

DO $$
DECLARE
  n int;
BEGIN
  LOOP
    DELETE FROM orders
    WHERE ctid IN (SELECT ctid FROM orders WHERE created_at < now() - interval '2 years' LIMIT 10000);
    GET DIAGNOSTICS n = ROW_COUNT;
    EXIT WHEN n = 0;
    COMMIT;
  END LOOP;
END $$;

Note: Test with a SELECT count(*) with the same condition first. COMMIT inside a DO block needs PostgreSQL 11 or later.

15. Monitoring & Capacity 8 scripts

growth, health check, disk space, workload, logs, exporter user

β–Ά15.1Daily health check scriptShellRead-only

Run as the postgres OS user, from cron. One script that checks the service, connections, replication, archiving, wraparound, long transactions and disk space, and prints OK or WARNING for each.

#!/bin/bash
Q() { psql -At -c "$1"; }
chk() { [ "$2" = "1" ] && echo "WARNING: $1" || echo "OK:      $1"; }

pg_isready -q || { echo "CRITICAL: PostgreSQL is not accepting connections"; exit 2; }

PCT=$(Q "SELECT round(100.0*count(*)/current_setting('max_connections')::int) FROM pg_stat_activity")
chk "connections used: ${PCT}%" $([ "$PCT" -gt 80 ] && echo 1 || echo 0)

XID=$(Q "SELECT max(age(datfrozenxid)) FROM pg_database")
chk "oldest transaction id age: $XID" $([ "$XID" -gt 1000000000 ] && echo 1 || echo 0)

LONG=$(Q "SELECT count(*) FROM pg_stat_activity WHERE xact_start < now() - interval '30 minutes' AND state <> 'idle'")
chk "transactions older than 30 min: $LONG" $([ "$LONG" -gt 0 ] && echo 1 || echo 0)

ARCH=$(Q "SELECT failed_count FROM pg_stat_archiver")
chk "failed WAL archive attempts: $ARCH" $([ "${ARCH:-0}" -gt 0 ] && echo 1 || echo 0)

SLOTS=$(Q "SELECT count(*) FROM pg_replication_slots WHERE NOT active")
chk "inactive replication slots: $SLOTS" $([ "$SLOTS" -gt 0 ] && echo 1 || echo 0)

for MP in /pgdata /pglogs /pgarch /pgbackup; do
  USE=$(df --output=pcent $MP 2>/dev/null | tail -1 | tr -dc '0-9')
  [ -n "$USE" ] && chk "disk $MP: ${USE}% used" $([ "$USE" -gt 85 ] && echo 1 || echo 0)
done

Note: Run it from cron every 5 to 15 minutes and send the output by email or to your monitoring tool.

β–Ά15.2Track database size growth every daySQL (psql)Changes something

Run in psql, then schedule the INSERT daily. Keeps one size row per database and day, so you can see growth and plan disk space.

CREATE TABLE IF NOT EXISTS public.db_size_history (
  captured_on date NOT NULL DEFAULT current_date,
  datname     name NOT NULL,
  size_bytes  bigint NOT NULL,
  PRIMARY KEY (captured_on, datname)
);

INSERT INTO public.db_size_history (datname, size_bytes)
SELECT datname, pg_database_size(datname) FROM pg_database WHERE NOT datistemplate
ON CONFLICT DO NOTHING;

-- Growth per database over the last 30 days
SELECT datname, pg_size_pretty(max(size_bytes) - min(size_bytes)) AS growth_30d, pg_size_pretty(max(size_bytes)) AS now_size
FROM public.db_size_history
WHERE captured_on > current_date - 30
GROUP BY datname ORDER BY max(size_bytes) - min(size_bytes) DESC;
β–Ά15.3Workload per database: rollbacks, deadlocks, temp filesSQL (psql)Read-only

Run in psql. Counters since the last statistics reset. High rollback numbers, deadlocks or temp file use point to application or memory problems.

SELECT datname, numbackends, xact_commit, xact_rollback,
       round(100.0 * xact_rollback / NULLIF(xact_commit + xact_rollback, 0), 2) AS rollback_pct,
       deadlocks, temp_files, pg_size_pretty(temp_bytes) AS temp_size, conflicts, stats_reset
FROM pg_stat_database
WHERE datname IS NOT NULL
ORDER BY xact_commit DESC;
β–Ά15.4Most written tables and HOT update ratioSQL (psql)Read-only

Run in psql inside the database. Tables with the most inserts, updates and deletes. A low HOT ratio on an update-heavy table means a lower fillfactor or fewer indexes could help.

SELECT relname, n_tup_ins, n_tup_upd, n_tup_del, n_tup_hot_upd,
       round(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables
ORDER BY n_tup_ins + n_tup_upd + n_tup_del DESC
LIMIT 15;
β–Ά15.5Disk space alert for the data, WAL and backup volumesShellRead-only

Run as root or postgres, from cron. Prints a line for every mount point above the limit.

#!/bin/bash
LIMIT=85
for MP in /pgdata /pglogs /pgarch /pgbackup; do
  USE=$(df --output=pcent $MP 2>/dev/null | tail -1 | tr -dc '0-9')
  [ -n "$USE" ] && [ "$USE" -ge "$LIMIT" ] && echo "ALERT: $MP is ${USE}% full on $(hostname)"
done
β–Ά15.6Most frequent errors in the server logShellRead-only

Run as the postgres OS user. Groups the ERROR, FATAL and PANIC lines of the log, so the most common problems appear first.

LOG=/pglogs/pgsql-17/logs
grep -h -E "ERROR|FATAL|PANIC" $LOG/*.log | sed -E 's/^[0-9: .-]+ [A-Z]+ \[[0-9]+\] [^ ]* //' | cut -c1-120 | sort | uniq -c | sort -nr | head -20

# Slow statements logged by log_min_duration_statement
grep -h "duration:" $LOG/*.log | tail -20
β–Ά15.7Create a monitoring user for Prometheus or other toolsSQL (psql)Changes something

Run in psql as a superuser. pg_monitor gives read access to all monitoring views without superuser rights.

CREATE USER exporter WITH PASSWORD 'ChangeMe_Strong_Password' CONNECTION LIMIT 5;
GRANT pg_monitor TO exporter;
ALTER ROLE exporter SET statement_timeout = '30s';

-- pg_hba.conf:  host  all  exporter  192.168.1.20/32  scram-sha-256
β–Ά15.8Temporary file usageSQL (psql)Read-only

Run in psql. Sorts and hash joins that do not fit in work_mem write temporary files. Find the queries that do this the most.

SELECT calls, temp_blks_written, pg_size_pretty(temp_blks_written * 8192) AS temp_written, left(query, 90) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC
LIMIT 10;

SHOW work_mem;
-- Test a bigger value in one session before you change it for everybody
-- SET work_mem = '128MB';

16. Maintenance & Automation 7 scripts

cron, pg_cron, reindex, .pgpass, safe stop and start

β–Ά16.1Weekly maintenance scriptShellChanges something

Run as the postgres OS user, from cron on a quiet night. Refreshes statistics, cleans old logs, and writes a size report. Autovacuum handles normal vacuuming.

#!/bin/bash
LOG=/pglogs/maintenance.log
echo "=== $(date) start ===" >> $LOG

vacuumdb --all --analyze-only --jobs=2 >> $LOG 2>&1

psql -At -c "SELECT datname || ' ' || pg_size_pretty(pg_database_size(datname)) FROM pg_database WHERE NOT datistemplate" >> $LOG

find /pglogs -name '*.log' -mtime +30 -delete
find /pgbackup/logical -type f -mtime +14 -delete

echo "=== $(date) end ===" >> $LOG
β–Ά16.2Cron entries for the postgres userShellChanges something

Run as the postgres OS user with crontab -e. A typical schedule for backups, the health check and maintenance. Write the output to a log file.

# m  h  dom mon dow  command
30  1  *   *   *    /home/postgres/backup_logical.sh   >> /pglogs/cron.log 2>&1
0   2  *   *   0    /home/postgres/backup_base.sh      >> /pglogs/cron.log 2>&1
*/10 * *   *   *    /home/postgres/health_check.sh     >> /pglogs/health.log 2>&1
0   3  *   *   6    /home/postgres/weekly_maint.sh     >> /pglogs/cron.log 2>&1

Note: Use full paths in cron. Cron has a very small PATH, so also add PATH=/usr/pgsql-17/bin:/usr/bin at the top of the crontab.

β–Ά16.3Schedule SQL jobs inside the database with pg_cronSQL (psql)Changes something

Run in psql as a superuser. pg_cron needs shared_preload_libraries and a restart. Jobs run as the user that created them.

-- postgresql.conf (restart required):
--   shared_preload_libraries = 'pg_cron'
--   cron.database_name = 'postgres'

CREATE EXTENSION pg_cron;

SELECT cron.schedule('nightly-analyze', '0 2 * * *', 'ANALYZE');
SELECT cron.schedule('refresh-sales',   '*/30 * * * *', 'REFRESH MATERIALIZED VIEW CONCURRENTLY mv_daily_sales');

SELECT jobid, jobname, schedule, command, active FROM cron.job;
SELECT jobid, status, return_message, start_time FROM cron.job_run_details ORDER BY start_time DESC LIMIT 10;

-- Remove a job
-- SELECT cron.unschedule('nightly-analyze');
β–Ά16.4Rebuild indexes onlineShellChanges something

Run as the postgres OS user. REINDEX CONCURRENTLY does not block writes. It needs extra disk space and time for each index.

# One table
psql -d appdb -c "REINDEX TABLE CONCURRENTLY public.orders"

# The whole database, 2 parallel jobs
reindexdb --concurrently --jobs=2 -d appdb

# Check for invalid indexes afterwards
psql -d appdb -c "SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid"
β–Ά16.5Store passwords safely for scripts with .pgpass and a service fileShellChanges something

Run as the postgres OS user. Scripts and cron jobs should never contain passwords. PostgreSQL reads them from ~/.pgpass.

cat > ~/.pgpass <<'EOF'
# host:port:database:user:password
192.168.1.10:5432:*:replicator:ChangeMe_Strong_Password
127.0.0.1:5432:*:postgres:ChangeMe_Strong_Password
EOF
chmod 600 ~/.pgpass

# Optional: connection names in ~/.pg_service.conf
cat > ~/.pg_service.conf <<'EOF'
[primary]
host=192.168.1.10
port=5432
user=postgres
dbname=appdb
EOF
psql "service=primary" -c "SELECT now()"

Note: .pgpass is ignored if its permissions are wider than 600.

β–Ά16.6Safe stop, start and restartShellChanges something

Run as root. A checkpoint before the stop makes the shutdown and the next start faster. Always check the log after a start.

psql -c "CHECKPOINT"
systemctl stop postgresql-17
systemctl start postgresql-17
tail -30 /pglogs/pgsql-17/logs/postgresql-$(date +%a).log
psql -c "SELECT now() - pg_postmaster_start_time() AS uptime"

# Reload the configuration without a restart
systemctl reload postgresql-17

Note: Do not use kill -9 on PostgreSQL processes. It forces a crash recovery.

β–Ά16.7Close idle connections automaticallySQL (psql)Changes something

Run in psql. Ends sessions that have been idle for more than 2 hours. Schedule with pg_cron or cron. Do not use it on pooler or monitoring users.

SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle'
  AND now() - state_change > interval '2 hours'
  AND usename NOT IN ('postgres', 'exporter', 'replicator')
  AND backend_type = 'client backend';

17. PgBouncer & Connection Pooling 4 scripts

install, configure, admin console, monitoring

β–Ά17.1Install and configure PgBouncerShellChanges something

Run as root. Transaction pooling keeps a small number of real connections for many clients. Create the password file with the hashes from PostgreSQL.

dnf install -y pgbouncer

cat > /etc/pgbouncer/pgbouncer.ini <<'EOF'
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
default_pool_size = 20
max_client_conn = 1000
admin_users = pgbouncer_admin
logfile = /var/log/pgbouncer/pgbouncer.log
EOF

# Create the user list from the database hashes
psql -At -c "SELECT '\"' || rolname || '\" \"' || rolpassword || '\"' FROM pg_authid WHERE rolname IN ('app_user','pgbouncer_admin')" > /etc/pgbouncer/userlist.txt
chown pgbouncer: /etc/pgbouncer/userlist.txt && chmod 640 /etc/pgbouncer/userlist.txt

systemctl enable --now pgbouncer
psql -h 127.0.0.1 -p 6432 -U app_user appdb -c "SELECT 1"

Note: pg_hba.conf on the database server must allow the PgBouncer host. Keep default_pool_size times the number of database and user pairs below max_connections.

β–Ά17.2PgBouncer admin console commandsSQL (psql)Read-only

Run after connecting with: psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer. Shows pools, clients and servers, and manages the pooler without a restart.

SHOW POOLS;       -- cl_waiting should be close to 0
SHOW STATS;
SHOW CLIENTS;
SHOW SERVERS;
SHOW CONFIG;

RELOAD;           -- re-read pgbouncer.ini
PAUSE appdb;      -- hold new queries, e.g. during a switchover
RESUME appdb;
β–Ά17.3Watch PgBouncer pools from the shellShellRead-only

Run as any user. Refreshes the pool overview every 2 seconds. A growing cl_waiting or maxwait means the pool is too small or queries are too slow.

watch -n 2 "psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c 'SHOW POOLS'"

tail -50 /var/log/pgbouncer/pgbouncer.log
β–Ά17.4Fix common PgBouncer errorsShellRead-only

Run in the shell. Quick checks for the usual error messages: too many clients, cannot connect to the server, and authentication failures.

# "no more connections allowed (max_client_conn)": raise max_client_conn and find the connection leak
grep -E "max_client_conn|no more connections" /var/log/pgbouncer/pgbouncer.log | tail -5

# "cannot connect to server": is PostgreSQL reachable from the PgBouncer host?
pg_isready -h 127.0.0.1 -p 5432
psql -h 127.0.0.1 -p 5432 -U app_user appdb -c "SELECT 1"

# "password authentication failed": regenerate the hash in userlist.txt, then reload
psql -At -c "SELECT '\"' || rolname || '\" \"' || rolpassword || '\"' FROM pg_authid WHERE rolname = 'app_user'"
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "RELOAD"

18. Upgrades & Migration 6 scripts

minor upgrade, pg_upgrade, checks, dump and restore, row counts

β–Ά18.1Pre-upgrade checksSQL (psql)Read-only

Run in psql in every database before a major upgrade. Lists extensions, open prepared transactions, replication slots and invalid indexes that can block or complicate the upgrade.

SELECT version();
SELECT extname, extversion FROM pg_extension ORDER BY extname;
SELECT count(*) AS prepared_transactions FROM pg_prepared_xacts;
SELECT slot_name, slot_type, active FROM pg_replication_slots;
SELECT indexrelid::regclass AS invalid_index FROM pg_index WHERE NOT indisvalid;
SELECT spcname, pg_tablespace_location(oid) FROM pg_tablespace WHERE spcname NOT LIKE 'pg_%';
SHOW data_checksums;

Note: The checksum setting of the new cluster must match the old one. Install the same extension packages for the new version before you start.

β–Ά18.2Minor upgrade on RHELShellChanges something

Run as root. Replaces the binaries and restarts. Upgrade the standbys first, then the primary. In a Patroni cluster switch over first and restart through patronictl.

dnf check-update 'postgresql17*'
dnf update -y 'postgresql17*'

psql -c "CHECKPOINT"
systemctl restart postgresql-17
psql -c "SELECT version()"
β–Ά18.3Major upgrade with pg_upgradeShellDangerous

Run as root and postgres. Example from 16 to 17 with hard links. Take a full backup first. After the new cluster has started, the old one can no longer be used with --link.

# 1. New cluster with the same encoding, locale and checksums as the old one
/usr/pgsql-17/bin/initdb -D /pgdata/pgsql-17/data -E UTF8 --locale=en_US.UTF-8 --data-checksums

# 2. Stop the old cluster
systemctl stop postgresql-16

# 3. Dry run: checks only, changes nothing
/usr/pgsql-17/bin/pg_upgrade -b /usr/pgsql-16/bin -B /usr/pgsql-17/bin \
   -d /pgdata/pgsql-16/data -D /pgdata/pgsql-17/data --link --check

# 4. The real upgrade
/usr/pgsql-17/bin/pg_upgrade -b /usr/pgsql-16/bin -B /usr/pgsql-17/bin \
   -d /pgdata/pgsql-16/data -D /pgdata/pgsql-17/data --link

# 5. Start the new cluster and rebuild the statistics
systemctl start postgresql-17
vacuumdb --all --analyze-in-stages

Note: Standby servers are not upgraded by pg_upgrade. Rebuild them from the new primary.

β–Ά18.4Tasks after a major upgradeShellChanges something

Run as the postgres OS user after the application has been tested. Updates extensions, removes the old cluster and starts the backups for the new version.

# Update every extension in each database
for DB in $(psql -At -c "SELECT datname FROM pg_database WHERE NOT datistemplate"); do
  psql -d "$DB" -At -c "SELECT format('ALTER EXTENSION %I UPDATE;', extname) FROM pg_extension WHERE extname <> 'plpgsql'" | psql -d "$DB"
done

# Remove the old cluster (script created by pg_upgrade)
./delete_old_cluster.sh

# Then: new full backup, rebuild standbys, restart WAL archiving, check the parameters
psql -c "SELECT version()"

Note: Old backups and old archived WAL belong to the old version and cannot restore the new cluster.

β–Ά18.5Move one database to another server with dump and restoreShellChanges something

Run from the new server. Streams the dump straight into the new server with parallel restore, so no big file is stored. Roles are moved first.

# Roles and tablespaces
pg_dumpall -h oldserver -U postgres --globals-only | psql -d postgres

# Create the database and copy the data
psql -d postgres -c "CREATE DATABASE appdb OWNER app_owner"
pg_dump -h oldserver -U postgres -d appdb -Fd -j 4 -f /pgbackup/appdb_dir
pg_restore -d appdb -j 4 -v /pgbackup/appdb_dir

vacuumdb -d appdb --analyze-in-stages

Note: Run the pg_dump of the NEW version against the old server, so it knows the newest features.

β–Ά18.6Compare row counts between source and targetShellRead-only

Run as the postgres OS user. Generates a count query for every table, runs it on both servers and shows the differences. Use it after a migration.

GEN="SELECT format('SELECT %L AS tbl, count(*) FROM %I.%I;', schemaname||'.'||tablename, schemaname, tablename) FROM pg_tables WHERE schemaname NOT IN ('pg_catalog','information_schema') ORDER BY 1"

psql -h oldserver -d appdb -At -c "$GEN" > /tmp/count.sql
psql -h oldserver -d appdb -At -F' ' -f /tmp/count.sql | sort > /tmp/count_old.txt
psql -h newserver -d appdb -At -F' ' -f /tmp/count.sql | sort > /tmp/count_new.txt
diff /tmp/count_old.txt /tmp/count_new.txt && echo "all row counts match"

19. Troubleshooting 10 scripts

will not start, cannot connect, disk full, slow server, too many connections, OOM

β–Ά19.1PostgreSQL will not startShellRead-only

Run as root. The log tells the real reason. The usual causes are a wrong data directory, a port in use, permissions, SELinux, a stale postmaster.pid or a bad parameter.

systemctl status postgresql-17 --no-pager -l
journalctl -u postgresql-17 -n 50 --no-pager
tail -50 /pglogs/pgsql-17/logs/postgresql-$(date +%a).log

ss -ltnp | grep 5432                              # is the port already used?
ls -ld /pgdata/pgsql-17/data                      # owner postgres, mode 700
cat /pgdata/pgsql-17/data/postmaster.pid          # stale file after a crash?
ausearch -m avc -ts recent | tail                 # SELinux denial
sudo -u postgres /usr/pgsql-17/bin/postgres -C data_directory -D /pgdata/pgsql-17/data   # configuration valid?

Note: Remove postmaster.pid only after you have confirmed with ps that no postgres process runs from that data directory.

β–Ά19.2Cannot connect to the databaseShellRead-only

Run from the client and the server. Goes through the layers in order: service, network, listening address, pg_hba.conf rule, then login.

# On the server
pg_isready -h 127.0.0.1 -p 5432
psql -c "SHOW listen_addresses" -c "SHOW port" -c "SHOW max_connections"
psql -c "SELECT line_number, type, database, user_name, address, auth_method FROM pg_hba_file_rules"
firewall-cmd --list-all

# From the client
nc -zv 192.168.1.10 5432
psql -h 192.168.1.10 -U app_user -d appdb

# The real reason is in the server log
grep FATAL /pglogs/pgsql-17/logs/*.log | tail
β–Ά19.3pg_wal is growing and the disk is filling upSQL (psql)Read-only

Run in psql and the shell. WAL is kept because archiving fails, a replication slot is inactive, wal_keep_size is large, or checkpoints are far behind. Find the reason before you do anything.

SELECT failed_count, last_failed_wal, last_failed_time FROM pg_stat_archiver;
SELECT slot_name, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;
SHOW wal_keep_size;
SHOW max_wal_size;

-- Shell: how big is pg_wal and how many files wait for the archiver?
--   du -sh /pgdata/pgsql-17/data/pg_wal
--   ls /pgdata/pgsql-17/data/pg_wal/archive_status/*.ready | wc -l

Note: Never delete files from pg_wal by hand. Fix the cause (archive target, stuck slot) and PostgreSQL removes the files itself.

β–Ά19.4Disk is full: emergency stepsShellDangerous

Run as root. Free space safely so PostgreSQL can continue. Look for old logs, old backups and core files first. Do not touch pg_wal, base or pg_xact.

df -h
du -xh / --max-depth=2 2>/dev/null | sort -rh | head -20

# Safe places to free space
find /pglogs -name '*.log' -mtime +7 -delete
find /pgbackup -maxdepth 1 -name 'base_*' -mtime +7 -exec rm -rf {} \;
ls -lh /pgdata/pgsql-17/data/base/pgsql_tmp 2>/dev/null     # leftover temp files after a crash
journalctl --vacuum-size=200M

Note: If PostgreSQL has already stopped because pg_wal is full, free space elsewhere on the same volume, then start it. Do not delete WAL files.

β–Ά19.5The server is slow: quick triageSQL (psql)Read-only

Run in psql while the problem is happening. Look at what is running, what is waiting, who is blocking, and whether vacuum or checkpoints are busy.

SELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE state = 'active' GROUP BY 1, 2 ORDER BY 3 DESC;

SELECT pid, usename, now() - query_start AS running_for, left(query, 80) AS query
FROM pg_stat_activity WHERE state = 'active' AND pid <> pg_backend_pid() ORDER BY query_start LIMIT 10;

SELECT count(*) AS blocked_sessions FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
SELECT pid, phase, relid::regclass FROM pg_stat_progress_vacuum;
SELECT num_timed, num_requested FROM pg_stat_checkpointer;

-- Shell: CPU, memory and disk:  top -c   |   vmstat 2 5   |   iostat -x 2 5
β–Ά19.6A query suddenly became slowSQL (psql)Read-only

Run in psql. Compare the plan with the estimates, check the statistics and the table health, and look for a recent change in the data volume.

-- 1. The plan: are estimated rows far from actual rows?
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE status = 'PENDING';

-- 2. Fresh statistics?
SELECT relname, last_analyze, last_autoanalyze, n_mod_since_analyze FROM pg_stat_user_tables WHERE relname = 'orders';
ANALYZE orders;

-- 3. Bloat or dead rows?
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum FROM pg_stat_user_tables WHERE relname = 'orders';

-- 4. Is an index missing or invalid?
SELECT indexrelid::regclass, indisvalid FROM pg_index WHERE indrelid = 'orders'::regclass;
β–Ά19.7"Too many connections" errorSQL (psql)Changes something

Run in psql as a superuser (superusers have reserved connections). Find who uses the connections and free them. The lasting fix is a connection pooler and fixing connection leaks.

SELECT usename, datname, application_name, state, count(*)
FROM pg_stat_activity GROUP BY 1, 2, 3, 4 ORDER BY count DESC LIMIT 15;

-- Free idle connections
SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE state = 'idle' AND now() - state_change > interval '10 minutes' AND usename <> 'postgres';

SHOW max_connections;
SHOW superuser_reserved_connections;

Note: Raising max_connections needs a restart and uses more memory. Use PgBouncer first.

β–Ά19.8The standby fell behind and cannot catch upShellChanges something

Run on the standby. "requested WAL segment has already been removed" means the primary no longer has the WAL. Use the archive, or rebuild the standby.

tail -30 /pglogs/pgsql-17/logs/postgresql-$(date +%a).log

# Option 1: fetch the missing WAL from the archive (add to postgresql.conf, then restart)
#   restore_command = 'cp /pgarch/pgsql-17/arch/%f %p'

# Option 2: rebuild the standby
systemctl stop postgresql-17
rm -rf /pgdata/pgsql-17/data/*
sudo -u postgres pg_basebackup -h 192.168.1.10 -U replicator -D /pgdata/pgsql-17/data -Fp -X stream -R -P
systemctl start postgresql-17
β–Ά19.9Out-of-memory kills and memory usageShellRead-only

Run as root. If the Linux OOM killer stopped PostgreSQL, look at the kernel log, the number of connections and work_mem.

dmesg -T | grep -i -E "out of memory|oom|killed process" | tail
journalctl -k | grep -i oom | tail

free -h
ps -eo pid,rss,cmd --sort=-rss | grep '[p]ostgres' | head -10
psql -c "SHOW work_mem" -c "SHOW max_connections" -c "SHOW shared_buffers"
sysctl vm.overcommit_memory

Note: work_mem is used per sort or hash step and per connection, so a large value times many connections can use all the memory. Set vm.overcommit_memory = 2 on dedicated database servers.

β–Ά19.10Check the database for corruptionShellRead-only

Run as the postgres OS user. pg_amcheck checks tables and B-tree indexes while the server runs. pg_checksums verifies all files but only with the server stopped.

# Online check of tables and indexes
pg_amcheck -d appdb --heapallindexed --jobs=2

# Offline check of all data files (server stopped)
systemctl stop postgresql-17
sudo -u postgres /usr/pgsql-17/bin/pg_checksums --check -D /pgdata/pgsql-17/data
systemctl start postgresql-17

Note: A corrupted index can be rebuilt with REINDEX. Corrupted table data means restoring from backup. Check the storage and memory as well.

PG DBA Scripts 1.0.3