PostgreSQL System Administration Functions

Complete reference for PostgreSQL system administration functions covering configuration reloading, backend process control, advisory locks, WAL management, and visibility map operations. Includes pg_cancel_backend(), pg_terminate_backend(), pg_reload_conf(), and pg_advisory_lock(). Updated for PostgreSQL 16.

10 functions

What are PostgreSQL System Administration Functions?

PostgreSQL system administration functions are used by DBAs to manage server configuration, terminate sessions, control checkpoints, and coordinate application-level locking. pg_cancel_backend() sends an interrupt to a running query, pg_terminate_backend() forcibly disconnects a session, and pg_reload_conf() reloads postgresql.conf without a full restart. Advisory locks (pg_advisory_lock and pg_advisory_xact_lock) provide application-level mutual exclusion.

pg_reload_conf

PG 8.0+boolean

Sends a SIGHUP signal to the server, causing it to reload configuration files (postgresql.conf, pg_hba.conf). Requires superuser privilege.

SecurityDBA

Signature

pg_reload_conf ( ) → boolean

Examples

sql
SELECT pg_reload_conf();
true (if successful)
Anti-Pattern

Many `postgresql.conf` settings can be changed without a server restart — just reload with `pg_reload_conf()`. Check `pg_settings.context = 'sighup'` to identify reloadable parameters.

example
SELECT name, setting FROM pg_settings WHERE context = 'sighup' AND name LIKE 'log_%';
Log settings changeable without restart

pg_terminate_backend

PG 8.0+boolean

Terminates a backend process (disconnects the client). Returns true if the signal was sent successfully. Requires superuser or pg_signal_backend role.

SecurityDBA

Signature

pg_terminate_backend ( pid integer [, timeout bigint] ) → boolean

Parameters

ParameterTypeDescription
pidintegerProcess ID of the backend to terminate
timeoutbigintOptional: wait up to this many milliseconds for termination to complete

Examples

sql
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND query_start < now() - interval '1 hour';
Terminates long-idle sessions
sql
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'old_db' AND pid <> pg_backend_pid();
Disconnect all other sessions from a database
Anti-Pattern

`pg_cancel_backend` sends SIGINT (cancels the current query but keeps the connection). `pg_terminate_backend` sends SIGTERM (kills the entire connection). Try cancel first, then terminate if needed.

example
SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE query_start < now() - interval '5 min' AND state = 'active';
Cancels long-running queries gracefully

pg_cancel_backend

PG 8.0+boolean

Cancels the current query being run by a backend process (sends SIGINT). The connection remains open.

DBAReliability

Signature

pg_cancel_backend ( pid integer ) → boolean

Parameters

ParameterTypeDescription
pidintegerProcess ID of the backend whose query to cancel

Examples

sql
SELECT pg_cancel_backend(1234);
true
sql
SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE query_start < now() - interval '30 seconds' AND state = 'active' AND pid <> pg_backend_pid();
Cancels queries running longer than 30 seconds
Anti-Pattern

`pg_cancel_backend` only interrupts the current query — the connection persists and the application can retry. `pg_terminate_backend` kills the entire connection. Use cancel for runaway queries in production, terminate for stuck/zombie connections.

example
-- Add to a monitoring script:
SELECT pid, query_start, query FROM pg_stat_activity WHERE state = 'active' AND query_start < now() - interval '1 min' AND query NOT LIKE 'SELECT pg_%';
Identify long-running queries to consider cancelling

pg_rotate_logfile

PG 8.0+boolean

Forces log file rotation when using PostgreSQL's built-in logging collector. Creates a new log file immediately.

DBAReliability

Signature

pg_rotate_logfile ( ) → boolean

Examples

sql
SELECT pg_rotate_logfile();
true
Anti-Pattern

Call `pg_rotate_logfile()` before long maintenance windows to start a clean log file. Makes it easier to extract maintenance-period logs for analysis.

example
SELECT pg_rotate_logfile(); -- Start fresh log before VACUUM FULL or migration
New log file created at current timestamp

pg_column_size

integer

Returns the number of bytes used to store the specified value (not the column definition, but an actual data value).

DBAReliability

Signature

pg_column_size ( any ) → integer

Parameters

ParameterTypeDescription
valueanyValue to measure the stored size of

Examples

sql
SELECT pg_column_size(1::integer);
4
sql
SELECT pg_column_size('hello'::text);
10
sql
SELECT pg_column_size('{}'::jsonb);
20
Anti-Pattern

Use `pg_column_size` to compare how much space different representations use. For example, `jsonb` vs normalized table columns, or different numeric precision levels.

example
SELECT pg_column_size(42::int), pg_column_size(42::bigint), pg_column_size(42::numeric);
4 | 8 | 7 — integer is most compact for small numbers

set_config

text

Sets a configuration parameter to the given value. If is_local is true, the setting reverts at the end of the transaction.

DBAReliability

Signature

set_config ( parameter_name text, new_value text, is_local boolean ) → text

Parameters

ParameterTypeDescription
parameter_nametextGUC parameter name (same as SET command)
new_valuetextNew value for the parameter
is_localbooleanIf true, only applies for current transaction (SET LOCAL)

Examples

sql
SELECT set_config('search_path', 'myschema, public', false);
myschema, public
sql
SELECT set_config('app.current_user_id', '42', true);
42 (reverts after transaction)
sql
SELECT set_config('timezone', 'America/New_York', false);
America/New_York
Anti-Pattern

Use custom GUC variables (with `app.` prefix) set via `set_config('app.current_user_id', id, true)` to pass application context to RLS policies and triggers — without changing the database role.

example
-- In application connection setup:
SELECT set_config('app.user_id', $1::text, false);
-- In RLS policy:
CREATE POLICY user_rows ON data USING (user_id = current_setting('app.user_id')::bigint);
Multi-tenant RLS without changing database roles

current_setting

text

Returns the current value of a configuration parameter. With missing_ok=true, returns NULL instead of error for unknown settings.

DBAReliability

Signatures

current_setting ( setting_name text ) → text
current_setting ( setting_name text, missing_ok boolean ) → text

Parameters

ParameterTypeDescription
setting_nametextGUC parameter name
missing_okbooleanIf true, return NULL for unknown settings instead of raising an error

Examples

sql
SELECT current_setting('timezone');
UTC
sql
SELECT current_setting('app.user_id', true);
42 (or NULL if not set)
sql
SELECT current_setting('server_version_num')::integer;
180000 (for PG 18)
Anti-Pattern

Use `current_setting('app.key', true)` with `missing_ok=true` in RLS policies and functions to safely read application context set by `set_config`. The `true` parameter prevents errors when the setting hasn't been set yet.

example
CREATE FUNCTION get_current_tenant() RETURNS bigint AS $ SELECT coalesce(current_setting('app.tenant_id', true), '0')::bigint; $ LANGUAGE SQL STABLE;
Returns tenant ID from session context, 0 if not set

pg_advisory_lock

PG 8.2+void

Obtains an exclusive session-level advisory lock. The application defines what the lock key means. Blocks until the lock is available.

SecurityDBAReliability

Signatures

pg_advisory_lock ( key bigint ) → void
pg_advisory_lock ( key1 integer, key2 integer ) → void

Parameters

ParameterTypeDescription
keybigint or two integersApplication-defined lock identifier

Examples

sql
SELECT pg_advisory_lock(12345);
(acquires lock 12345)
sql
SELECT pg_advisory_lock(hashtext('my_job_name'));
Named lock using hash
Anti-Pattern

Advisory locks are ideal for preventing duplicate job execution across multiple application servers. Use `pg_try_advisory_lock` for non-blocking acquisition — if it returns false, another process has the lock.

example
-- Non-blocking: skip if already locked
IF pg_try_advisory_lock(hashtext('process_invoices')) THEN
  -- do work
  PERFORM pg_advisory_unlock(hashtext('process_invoices'));
END IF;
Safe distributed mutex for job scheduling

pg_try_advisory_lock

PG 8.2+boolean

Attempts to acquire a session-level advisory lock. Returns true if successful, false if the lock is not available (non-blocking).

SecurityDBAReliability

Signatures

pg_try_advisory_lock ( key bigint ) → boolean
pg_try_advisory_lock ( key1 integer, key2 integer ) → boolean

Parameters

ParameterTypeDescription
keybigint or two integersApplication-defined lock identifier

Examples

sql
SELECT pg_try_advisory_lock(42);
true (if lock acquired), false (if already locked)
sql
SELECT * FROM jobs WHERE pg_try_advisory_lock(id) LIMIT 1;
Selects and locks one unlocked job
Anti-Pattern

Use `pg_try_advisory_lock(id)` in a SELECT to implement a concurrent job queue: `SELECT id FROM jobs WHERE status = 'pending' AND pg_try_advisory_lock(id) LIMIT 1 FOR UPDATE SKIP LOCKED`. Multiple workers can safely claim different jobs.

example
SELECT id FROM pending_jobs WHERE pg_try_advisory_lock(id) ORDER BY created_at LIMIT 1;
Claims one unclaimed job per worker call

pg_advisory_unlock

PG 8.2+boolean

Releases a session-level advisory lock previously acquired with pg_advisory_lock or pg_try_advisory_lock.

SecurityDBAReliability

Signatures

pg_advisory_unlock ( key bigint ) → boolean
pg_advisory_unlock_all ( ) → void

Parameters

ParameterTypeDescription
keybigint or two integersLock identifier to release

Examples

sql
SELECT pg_advisory_unlock(12345);
true (released), false (wasn't held)
sql
SELECT pg_advisory_unlock_all();
Releases all advisory locks held by this session
Anti-Pattern

Session-level advisory locks persist until explicitly released or the session ends. Always pair `pg_advisory_lock` with `pg_advisory_unlock`. Use transaction-level `pg_advisory_xact_lock` if you want automatic release at transaction end.

example
-- Transaction-level: auto-released at commit/rollback
SELECT pg_advisory_xact_lock(42);
Lock released automatically when transaction ends

Related PostgreSQL Categories