Bookmarks
ReferenceData & AIBackendVerified

PostgreSQL

PostgreSQL (Postgres) is an object-relational database management system for applications. This reference covers psql, types and indexes, MVCC and VACUUM, EXPLAIN, replication and backups.

checked 1 Nov · next check 8 Nov · 63 min read

Sections
13
Reading
63 min
Current version
18.6
Written from
postgresql.org/docs/current

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What PostgreSQL is and how it works

PostgreSQL is an open-source object-relational database management system (DBMS). The server stores databases and runs clients’ SQL queries, while transactions and the write-ahead log (WAL) keep data intact under concurrent access and crashes.

People choose PostgreSQL as an application’s main database when data must stay consistent: it has transactions, foreign keys, triggers, complex queries and multiversion concurrency control (MVCC), where readers and writers do not block each other. You can extend it with your own data types, functions, operators and index methods. The licence permits free use, including in commercial products. If you are choosing between PostgreSQL and a column-oriented DBMS for analytics, see the ClickHouse reference, section “What ClickHouse is and how it works”.

Processes and memory

PostgreSQL uses a client/server model, and the client can be on another machine. The first process of an instance, the postmaster, waits for connections and starts a separate server process (backend) for each one; from then on the client talks only to that process. The instance’s processes exchange data through shared memory, which holds copies of table and index pages (shared buffers) and a temporary area for WAL records.

Modified pages are not written to disk straight away. On COMMIT, only the WAL records are flushed to disk: the log is written sequentially, which is cheaper than writing every modified page. The pages themselves are written later by the background writer and checkpointer processes, and after a crash the server replays the changes from the WAL. That is why the WAL is what keeps data durable.

The accent marks the path that durability depends on: flushing the WAL to disk on COMMIT.

There are several background processes. The WAL writer moves WAL records from shared memory to files in the background, and autovacuum regularly runs vacuuming and gathers statistics. The postmaster starts and supervises all of an instance’s background processes.

The path of a query

Every query goes through four stages:

  1. Parser: checks the syntax and builds the query tree.
  2. Rewrite: applies rules, for example replacing a view’s name with its definition.
  3. Planner: considers the possible paths, such as a full table scan or an index lookup, and picks the cheapest by estimated cost.
  4. Executor: walks the plan, reads rows, sorts and joins; the result rows go to the client.

EXPLAIN shows which plan was chosen; see the section “Performance and EXPLAIN”.

Cluster, databases and schemas

One server instance manages exactly one database cluster: a set of databases and the objects they share, such as roles. The initdb program creates the cluster. Inside a database, objects live in schemas, which are namespaces, and tables live in schemas. You can run several instances on one machine as long as their TCP ports differ. For details, see the section “Data model and types”.

What you should know first

  • The query language: SELECT, joins, grouping and transactions are covered in the SQL reference.
  • The Linux command line, users and file permissions are covered in the Linux reference.
  • Services and their logs are covered in the systemd reference.

Section sources

the section is written from these pages

Cheat sheet: psql and administration

Everyday commands: psql, roles and databases, indexes and plans, sessions, maintenance and backups. Replace the names in the examples (shop, app, orders) with your own; see the other sections of the reference for details.

psql

TaskCommand
List databases\l
Connect to the shop database\c shop
Current connection parameters\conninfo
Tables in the search path schemas\dt
A table’s columns, indexes and constraints\d orders
Indexes\di
Roles and their attributes\du
Privileges on a table\dp orders
Show wide rows vertically when they do not fit\x auto
Show the time of every query\timing on
Help on an SQL command\h CREATE INDEX
Quit\q

Connecting

TaskCommand
Log in on this machine as postgressudo -u postgres psql
Connect to a server on the networkpsql -h 192.0.2.10 -U app -d shop
The same, with a connection stringpsql "postgresql://app@192.0.2.10:5432/shop"
Run one command and exitpsql -d shop -c 'SELECT count(*) FROM orders'
Run a filepsql -d shop -f migrate.sql

Roles and databases

TaskCommand
A role that can log inCREATE ROLE app LOGIN;
Set a password without echoing it\password app
A database with an ownerCREATE DATABASE shop OWNER app;
Let a role create databasesALTER ROLE app CREATEDB;
Permission to read a tableGRANT SELECT ON orders TO analyst;
Database sizeSELECT pg_size_pretty(pg_database_size('shop'));
Table size including indexesSELECT pg_size_pretty(pg_total_relation_size('orders'));

Indexes and plans

TaskCommand
An index without blocking writesCREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);
Query planEXPLAIN SELECT * FROM orders WHERE customer_id = 42;
Plan with actual timingsEXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;
Refresh a table’s statisticsANALYZE orders;
The heaviest queriesSELECT query, calls, total_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
Indexes that have never been scannedSELECT indexrelname FROM pg_stat_user_indexes WHERE idx_scan = 0;

Sessions and locks

TaskCommand
Who is connected and what they are runningSELECT pid, usename, state, query FROM pg_stat_activity;
Who is blocking whomSELECT pid, pg_blocking_pids(pid) FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
Locks that are currently being waited forSELECT * FROM pg_locks WHERE NOT granted;
Cancel a session’s current querySELECT pg_cancel_backend(12345);
Reload the configuration filesSELECT pg_reload_conf();

Maintenance

TaskCommand
Vacuum a table and refresh its statisticsVACUUM (ANALYZE) orders;
Vacuum with a detailed reportVACUUM (VERBOSE) orders;
Where the most dead row versions areSELECT relname, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;
Progress of a running vacuumSELECT * FROM pg_stat_progress_vacuum;
Age of unfrozen transactions per databaseSELECT datname, age(datfrozenxid) FROM pg_database;

Backups

TaskCommand
Dump a database to a custom-format archivepg_dump -Fc -f shop.dump shop
Dump to a directory with 4 parallel jobspg_dump -Fd -j 4 -f shop_dir shop
Restore an archive into a newly created empty databasepg_restore -d shop_restored shop.dump
The cluster’s roles and tablespacespg_dumpall --globals-only -f globals.sql
A physical copy of the whole clusterpg_basebackup -D /backup/base -Ft -z -P

Dangerous commands

TaskCommand
Delete a database with all its dataDROP DATABASE shop;
Delete all rows of a tableTRUNCATE orders;
Rewrite a table under an exclusive lockVACUUM FULL orders;
Terminate a session completelySELECT pg_terminate_backend(12345);

Section sources

the section is written from these pages

Installation and first run

On Ubuntu, install PostgreSQL from the PostgreSQL Apt repository (PGDG): it has every supported version, and fixes arrive through regular apt. Install the postgresql-18 package, check the version with psql --version, create a role and a database, and connect.

Linux: Ubuntu

The standard Ubuntu repositories also include PostgreSQL, but only one version, frozen for the whole life of that Ubuntu release. The PGDG repository is maintained by the PostgreSQL project; enable it with the script from the postgresql-common package and install the server:

bashon an Ubuntu server
sudo apt install -y postgresql-commonsudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.shsudo apt updatesudo apt install -y postgresql-18

The repository supports Ubuntu 26.04, 24.04 and 22.04 LTS, as well as 26.10; arm64 packages are built only for LTS releases. Manual setup, with the key and the /etc/apt/sources.list.d/pgdg.sources file, is described on the same download page. If the machine needs only the psql client, install the postgresql-client-18 package.

Windows

For Windows, the postgresql.org download page offers an interactive installer from EDB for all supported versions. It includes the server, the pgAdmin graphical client and the StackBuilder package manager for additional tools and drivers. The PostgreSQL 18 installer has been verified on Windows Server 2025 and 2022.

Checking the installation

The command prints the version of the psql client; the first connection to the server shows whether the server works.

bashon an Ubuntu server
psql --version
textexample output
psql (PostgreSQL) 18.x

First role and database

PostgreSQL roles are not operating system users. Right after installation there is a role named after the system user that the server was installed as, usually postgres. It is allowed to create roles and databases; use it to create an application role and a database:

bashon the server
# role app with a password: createuser will prompt for itsudo -u postgres createuser --pwprompt app# database shop, owned by the app rolesudo -u postgres createdb --owner=app shop

If createdb printed nothing, the database has been created. The messages role "app" does not exist and permission denied to create database are covered in the section “Common errors and diagnostics”.

Connecting with psql

A client needs a database, a server, a port and a role; in psql these are the -d, -h, -p and -U flags. Without -h, psql connects over a Unix socket to a server on the same machine. The default port is set at build time and is usually 5432, and the default role and database match the operating system user name.

bashon the client machine
# server on the network: role app, database shoppsql -h 192.0.2.10 -p 5432 -U app -d shop# the same with a single connection stringpsql "postgresql://app@192.0.2.10:5432/shop"

To avoid repeating the parameters, set the environment variables PGHOST, PGPORT, PGUSER and PGDATABASE. Do not put the password in the command: psql prompts for it, and scripts pass it through the ~/.pgpass file. On a successful login, psql prints its version and a prompt with the database name:

bashon the client machine
export PGHOST=192.0.2.10 PGUSER=app PGDATABASE=shoppsql
textexample output
psql (18.x)Type "help" for help. shop=>

Loading data from CSV

The COPY command does bulk loading; what matters is which machine holds the file. COPY … FROM 'file' reads a file on the server as the operating system user the server runs as; this is allowed only for a superuser and members of the pg_read_server_files role. The psql command \copy reads a file on your machine and sends the rows over the connection, so the INSERT privilege on the table is enough.

sqlin psql, file on the client
\copy orders FROM 'orders.csv' (FORMAT csv, HEADER)
sqlon the server, as a superuser
COPY orders FROM '/srv/import/orders.csv'    (FORMAT csv, HEADER);

HEADER skips the first row with the column names. If the file does not have all the columns, list them: \copy orders (customer_id, total) FROM …; the rest get their default values. Export goes the other way, with TO, and you can export the result of a query:

sqlin psql
\copy (SELECT id, total FROM orders) TO 'out.csv' (FORMAT csv, HEADER)

Server parameters are set in the postgresql.conf file and connection rules in pg_hba.conf; see the sections “Performance and EXPLAIN” and “Security: roles, privileges and access”.

Section sources

the section is written from these pages

Data model and types

PostgreSQL data lives in tables, tables live in schemas, and schemas live in the databases of one cluster. A column’s data type determines which values are allowed and how they are computed with. Use numeric for money, timestamptz for points in time and jsonb for JSON.

Cluster, databases and schemas

A cluster contains one or more databases, and they share roles. A connection always goes to one database and cannot see the data of other databases. A database contains schemas, which are namespaces for tables, types and functions. Tables with the same name can exist in different schemas, but schemas cannot be nested.

A table created without a schema goes into the public schema, which exists in every new database. A name without a schema is looked up along the search path, search_path; by default it is "$user", public: first the schema named after the current role, if one exists, then public. New objects are created in the first existing schema of the path.

sqlin psql
-- a separate schema for reportsCREATE SCHEMA reports;-- fully qualified name: schema.tableCREATE TABLE reports.daily (day date, total numeric(12, 2));-- look in reports first, then in publicSET search_path TO reports, public;SHOW search_path;

Numbers

TypeRange and sizeWhen to use
smallint−32,768 to 32,767, 2 bytesOnly when disk space matters
integer−2,147,483,648 to 2,147,483,647, 4 bytesThe usual choice for whole numbers
bigintabout ±9.2 · 10¹⁸, 8 bytesWhen integer is not enough: identifiers, if there will be more than 2³¹ of them
numeric(p, s)up to 131,072 digits before the decimal point and 16,383 after; exactMoney and anything that needs precision; slower than integers
realabout 6 significant digits, 4 bytes; approximateMeasurements where some error is acceptable
double precisionabout 15 significant digits, 8 bytes; approximateThe same, when you need more precision

numeric stores values exactly, while real and double precision store them approximately: a value you read back may differ slightly from the one you wrote. So store amounts in numeric with an explicit precision, for example numeric(12, 2): the value is rounded to 2 decimal places, and too many digits before the decimal point cause an error.

Strings, dates and other types

TypeWhat it stores
textA string of variable length
varchar(n)A string of variable length, at most n characters
char(n)A fixed-length string of n characters
booleanA logical value: true or false
dateA date without a time
timestampA date and time without a time zone
timestamptzA point in time: stored in UTC, displayed in the session’s time zone
intervalA span of time: interval '90 days'
uuidA universally unique identifier
jsonbJSON in a parsed binary form

For points in time, such as when an order was created or a payment arrived, use timestamptz. A value with an explicit time zone is converted to UTC and stored that way, while a value without a zone is taken to be in the session’s time zone, set by the TimeZone parameter. On output, the time is shown in the session’s zone. timestamp stores the date and time as they are: the application itself must know which moment that is.

sqlin psql
SET TimeZone = 'Asia/Tashkent';SELECT timestamptz '2026-10-31 09:00:00+00';
textexample output
      timestamptz------------------------ 2026-10-31 14:00:00+05(1 row)

Row identifiers

PostgreSQL generates row numbers in two ways: with the standard identity column, as in this section’s reference example, and with its own pseudo-types smallserial, serial and bigserial. serial is not a real type but a shorthand: it creates an integer column whose default value comes from a sequence. The numbers have gaps even without deletions, because a number is also consumed when a transaction rolls back. For identity syntax, see the SQL reference, section “Tables and constraints (DDL)”.

JSON and jsonb

There are two JSON types. json stores the input text as it is and parses it on every use. jsonb stores a parsed binary form: inserts are slightly slower, but processing is much faster and indexes are available. jsonb does not preserve whitespace, key order or duplicate keys; the last value is kept. The documentation recommends jsonb for most applications.

sqlin psql
-- gift orders and how they are deliveredSELECT id, attrs -> 'delivery' AS deliveryFROM ordersWHERE attrs @> '{"gift": true}';

The -> operator extracts the value for a key, and @> checks whether the document contains the given pair. A GIN index on the jsonb column speeds up queries with @>: CREATE INDEX ON orders USING gin (attrs);.

Reference example: the orders table

The orders table, with types chosen by these rules; the examples in the sections “Indexes” and “Performance and EXPLAIN” are built on it:

sqlshop database
CREATE TABLE orders (    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,    customer_id bigint NOT NULL,    status text NOT NULL DEFAULT 'new',    total numeric(12, 2) NOT NULL,    created_at timestamptz NOT NULL DEFAULT now(),    attrs jsonb);

Why these types: bigint for id and customer_id leaves room to grow, numeric(12, 2) stores the amount exactly, and timestamptz gives an unambiguous point in time. The jsonb column holds optional attributes that do not need a column of their own.

Section sources

the section is written from these pages

Indexes

An index is a separate structure that lets the server find rows without reading the whole table. By default, CREATE INDEX builds a B-tree, which speeds up equality lookups, ranges and sorting. An index is updated on every change to the table, so unneeded indexes slow down INSERT, UPDATE and DELETE.

How a B-tree works

A B-tree is a multi-level tree of pages. Internal pages point to pages one level down, leaf pages hold pointers to table rows, and pages on the same level are linked in a doubly linked list. A lookup descends from the root through internal pages to the right leaf, passing through only a few levels.

Usually more than 99% of an index’s pages are leaf pages; the numbers in the diagram are illustrative.
sqlin psql
-- an index for finding a customer’s ordersCREATE INDEX orders_customer_id_idx ON orders (customer_id);

A B-tree supports the operators <, <=, =, >=, >, as well as BETWEEN, IN, IS NULL and IS NOT NULL. It works for LIKE only if the pattern is anchored at the start of the string ('abc%'). If the database locale is not C, this needs an index with a special operator class.

Index types

TypeQueries it serves
B-treeEquality, ranges, sorting; the default type
HashEquality only (=)
GiSTGeometric types and nearest-neighbour search: ORDER BY location <-> point '(101,456)'
SP-GiSTNon-balanced structures: quadtrees, k-d trees, radix trees
GINValues made of many elements, such as arrays: element lookup, @>, &&
BRINColumns whose values follow the physical order of rows in the table, such as insertion time
sqlin psql
-- the index type is set with USINGCREATE INDEX orders_created_brin    ON orders USING brin (created_at);

Multicolumn indexes and column order

An index can cover several columns: up to 32, including INCLUDE columns. A multicolumn B-tree is most efficient when the conditions are on the leading (leftmost) columns. The part of the index that has to be scanned is narrowed by equality conditions on the leading columns and an inequality on the first column without an equality. Conditions on columns further right are checked inside the index, but do not always shorten the scan.

sqlin psql
-- the equality column first, then the range columnCREATE INDEX orders_cust_created_idx    ON orders (customer_id, created_at); SELECT id, totalFROM ordersWHERE customer_id = 42  AND created_at >= now() - interval '30 days';

Since PostgreSQL 18, a B-tree supports skip scan: an index on (customer_id, created_at) can also help a query that has a condition only on created_at. The planner picks such a plan when the first column has few distinct values; otherwise reading the table is cheaper. A single-column index is usually enough, and indexes with more than three columns are rarely useful.

Unique, partial and expression indexes

UNIQUE forbids duplicate values; by default, multiple NULLs are not counted as duplicates. A partial index with WHERE contains only some of the rows, for example new orders, if those are what you mostly search. An expression index stores the result of a function: lower(email) speeds up case-insensitive search. Functions in the expression and the condition must be immutable.

sqlin psql
CREATE UNIQUE INDEX customers_email_key    ON customers (lower(email)); CREATE INDEX orders_new_idx    ON orders (created_at)    WHERE status = 'new';

An expression index is used only if the query contains the same expression: WHERE lower(email) = 'a@example.com'. After creating such an index, run ANALYZE so the planner gets statistics for the expression.

Index-only scans and INCLUDE

If every column a query needs is in the index, the server can answer from the index without reading the table (an index-only scan). Non-key columns are added with INCLUDE: you cannot search by them, but they can be returned straight from the index. Add only narrow columns this way: they duplicate table data and make the index larger.

sqlin psql
CREATE INDEX orders_customer_total_idx    ON orders (customer_id) INCLUDE (total);

Building an index without blocking writes

A plain CREATE INDEX does not block reads, but it blocks INSERT, UPDATE and DELETE until the build finishes, and a large table can take hours to index. CREATE INDEX CONCURRENTLY does not block writes: it scans the table twice and waits for running transactions to finish, so it takes longer. It cannot run inside a transaction block.

sqlin psql
CREATE INDEX CONCURRENTLY orders_status_idx    ON orders (status);

Why an index is not used

  • The condition selects a large share of the rows: reading the table sequentially is cheaper than walking the index.
  • The condition is not in the form “column, operator, value”: for example, a function is applied to the column and there is no index on that expression.
  • The column order of the multicolumn index does not match the condition.
  • The statistics are out of date: run ANALYZE orders.

EXPLAIN shows which plan was chosen and why; see the section “Performance and EXPLAIN”, which also covers finding indexes that are never used. Drop rarely used indexes: each one slows down writes. The exception is UNIQUE and PRIMARY KEY indexes: they exist not for lookups but to check uniqueness on every write.

Section sources

the section is written from these pages

Transactions, MVCC and locks

PostgreSQL isolates transactions with multiversion concurrency control (MVCC): each query sees a snapshot of the data, so reads do not block writes and writes do not block reads. Waiting happens when two transactions change the same rows or a command takes a lock on a whole table.

Row versions and snapshots

A modified row gets a new version, and the old one stays for transactions that can still see it. A snapshot determines which versions a query sees. In Read Committed mode, it is the data committed before that query started; in Repeatable Read, the data committed before the transaction’s first query. This is why readers do not wait for writers.

Obsolete versions are later removed by VACUUM; see the section “VACUUM and autovacuum”.

Isolation levels in PostgreSQL

LevelWhat a query seesIs a retry needed
Read Committed (default)Data committed before that query startedNo, but two queries in the same transaction can see different data
Repeatable ReadData as of the transaction’s first queryYes, for a writing transaction, on a serialization failure
SerializableThe same, and the result is as if the transactions ran one after anotherYes, on any serialization failure

You can request Read Uncommitted, but in PostgreSQL it behaves as Read Committed. Repeatable Read is stricter than the standard here: phantom reads cannot occur at this level. The phenomena themselves (dirty reads, non-repeatable reads and phantom reads) are described in the SQL reference, in the section “Transactions and isolation levels”.

sqlin psql
BEGIN;SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;SELECT sum(total) FROM orders WHERE customer_id = 42;UPDATE orders SET status = 'paid' WHERE id = 1001;COMMIT;

Serialization failures and retries

At the Repeatable Read and Serializable levels, a transaction cannot modify a row that another transaction modified and committed after the first one started. The server rolls it back with an error:

textserver message
ERROR:  could not serialize access due to concurrent update

Serializable has a second form of this error: could not serialize access due to read/write dependencies among transactions. The response is the same: roll back the transaction and run it again from the start, when it will see the changes that have now been committed. Read-only transactions at Repeatable Read do not need a retry.

Row locks

UPDATE and DELETE lock the rows they affect until the end of the transaction. To lock rows when reading them, add a locking clause to SELECT. Use FOR UPDATE before changing a row, and FOR SHARE to prevent changes to a row while you rely on it. Ordinary reads are not affected by these locks: only writers and transactions that lock the same rows have to wait.

With NOWAIT, the query fails immediately instead of waiting, and SKIP LOCKED skips rows that are already locked. The latter suits a job queue consumed by several workers: each takes a free job and does not wait for the others. Do not use SKIP LOCKED for ordinary queries: it returns an incomplete view of the data.

sqla job queue
BEGIN;SELECT id, payloadFROM jobsWHERE status = 'queued'ORDER BY idLIMIT 1FOR UPDATE SKIP LOCKED;-- process the job and mark it as doneUPDATE jobs SET status = 'done' WHERE id = 17;COMMIT;

Table locks

Every command takes a table lock of the appropriate mode and holds it until the end of the transaction. Modes differ in which other modes they conflict with. SELECT, INSERT, UPDATE and DELETE do not block one another at the table level; the commands that wait are those that change the table’s structure or rewrite it.

CommandModeConflicts with
SELECTACCESS SHAREOnly ACCESS EXCLUSIVE
INSERT, UPDATE, DELETEROW EXCLUSIVESHARE and stronger modes, such as a plain CREATE INDEX
VACUUM, ANALYZE, CREATE INDEX CONCURRENTLYSHARE UPDATE EXCLUSIVESchema changes and another VACUUM; reads and writes go through
CREATE INDEXSHAREWrites to the table; reads go through
Many forms of ALTER TABLE, DROP TABLE, TRUNCATE, VACUUM FULL, REINDEXACCESS EXCLUSIVEEverything, including SELECT

Deadlocks

A deadlock is when two transactions wait for each other: the first holds row 1 and waits for row 2, and the second does the opposite. PostgreSQL detects this itself and aborts one of the transactions; which one cannot be predicted. To protect against it, take locks in the same order throughout the application, and retry the aborted transaction.

sqlhow a deadlock arises
-- session 1BEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 1;-- session 2BEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 2;UPDATE accounts SET balance = balance + 100 WHERE id = 1;-- session 1: now both sessions wait for each otherUPDATE accounts SET balance = balance + 100 WHERE id = 2;

Advisory locks

An advisory lock means whatever the application decides: the server does not know what the key protects. A transaction-level lock is released automatically when the transaction ends, which makes it a way to avoid running a job twice:

sqlin psql
BEGIN;-- key 42 is the job number; a second session will wait hereSELECT pg_advisory_xact_lock(42);-- run the jobCOMMIT;

Who is blocking whom

All server locks are visible in the pg_locks view; a lock that is being waited for has granted = false. Join pg_locks rows to pg_stat_activity on pid; the easiest way to get the chain of waits is the pg_blocking_pids() function, which returns the processes a session is waiting for.

sqlin psql
SELECT pid,       pg_blocking_pids(pid) AS blocked_by,       now() - query_start AS query_age,       queryFROM pg_stat_activityWHERE cardinality(pg_blocking_pids(pid)) > 0;

Unless a deadlock occurs, a transaction waits for a lock for as long as it takes. So do not keep a transaction open while the application waits for a user or an external service: all the locks it has taken are held until COMMIT or ROLLBACK.

Section sources

the section is written from these pages

VACUUM and autovacuum

VACUUM removes the dead row versions left behind by UPDATE and DELETE and makes their space available for new data. It is normally run by autovacuum; if autovacuum cannot keep up, tables bloat, and in the worst case the database stops accepting writes.

Why vacuuming is needed

UPDATE and DELETE do not remove the old version of a row immediately: other transactions may still see it. When no transaction needs a version any more, it becomes dead (a dead tuple) and only takes up space. A plain VACUUM removes dead versions from tables and indexes and marks the space as free for new rows, but as a rule does not shrink the table file.

System columns show whose version a row is: xmin is the ID of the transaction that inserted the version, and xmax is that of the transaction that deleted it (0 for a version that has not been deleted). Every UPDATE creates a new version of the same logical row:

sqlin psql
SELECT xmin, xmax, id, status FROM orders WHERE id = 1001;UPDATE orders SET status = 'paid' WHERE id = 1001;-- the new version has a different xminSELECT xmin, xmax, id, status FROM orders WHERE id = 1001;
A plain VACUUM frees space inside the table file; VACUUM FULL can shrink the file itself.

VACUUM, VACUUM FULL and ANALYZE

CommandWhat it does
VACUUM ordersRemoves dead versions and hands the space to new rows; reads and writes keep working
VACUUM (ANALYZE) ordersThe same, and also gathers statistics for the planner
ANALYZE ordersStatistics only: reads a random sample of rows, not the whole table
VACUUM (VERBOSE) ordersVacuuming with a detailed report on the table
VACUUM FULL ordersRewrites the table without empty space and returns that space to the OS; holds an ACCESS EXCLUSIVE lock and needs room for one more copy of the table while it runs

VACUUM cannot run inside a transaction block. Without a table name, it processes all tables in the current database that you are allowed to vacuum. This requires the MAINTAIN privilege on the table; the database owner can vacuum all of its tables.

How autovacuum works

Autovacuum is enabled by default. Every autovacuum_naptime, the autovacuum launcher starts a worker process in each database, and the worker runs VACUUM and ANALYZE on tables with enough accumulated changes. VACUUM is started for a table when the number of dead versions exceeds a threshold:

textthreshold formula
threshold = min(autovacuum_vacuum_max_threshold,                autovacuum_vacuum_threshold +                autovacuum_vacuum_scale_factor * number of rows)

With the default settings, a table of 1,000,000 rows is vacuumed when it has more than 200,050 dead versions: 50 + 0.2 × 1,000,000.

ParameterWhat it setsDefault
autovacuumWhether autovacuum is enabledon
autovacuum_naptimePause between passes over one database1min
autovacuum_max_workersHow many worker processes run at once3
autovacuum_vacuum_thresholdThe fixed part of the threshold50
autovacuum_vacuum_scale_factorThe share of the table’s rows included in the threshold0.2
autovacuum_vacuum_max_thresholdUpper limit of the threshold, since PostgreSQL 18100000000
autovacuum_analyze_scale_factorThe share of changed rows that triggers an automatic ANALYZE0.1
autovacuum_freeze_max_ageThe transaction age after which vacuuming is mandatory200000000

For a large, frequently updated table, it is better to lower the scale factor in the table’s own parameters; this does not affect other tables:

sqlin psql
ALTER TABLE orders SET (    autovacuum_vacuum_scale_factor = 0.02,    autovacuum_analyze_scale_factor = 0.01);

Freezing and the transaction counter

A transaction ID (XID) is 32-bit, and IDs are compared in a circle: for any transaction, two billion IDs count as the past and two billion as the future. So that old rows do not end up “in the future” and drop out of sight, VACUUM freezes them: frozen versions are visible to all transactions regardless of ID. Every table must be vacuumed at least once every two billion transactions.

The age of the oldest unfrozen transaction is shown by age(datfrozenxid) for databases and age(relfrozenxid) for tables. When it exceeds autovacuum_freeze_max_age, autovacuum is forced to run, even if it is disabled.

sqlin psql
SELECT datname, age(datfrozenxid) FROM pg_database;

If vacuuming still cannot keep up, warnings such as must be vacuumed within … transactions appear in the log 40 million transactions before the limit. At 3 million transactions before the limit, the server stops issuing new transaction IDs and accepts only reads. For what to do, see the section “Common errors and diagnostics”.

What blocks vacuuming

VACUUM does not remove a version that any transaction might still see. The usual causes are:

  • Long-running and forgotten open transactions: find them in pg_stat_activity by a large age(backend_xmin).
  • Unfinished prepared transactions (PREPARE TRANSACTION): they are listed in pg_prepared_xacts.
  • Replication slots for servers that no longer exist: they are visible in pg_replication_slots.
  • Frequent commands that conflict with autovacuum’s SHARE UPDATE EXCLUSIVE lock, such as ANALYZE: they interrupt it, and vacuuming may never finish.

Monitoring

sqlin psql
-- which tables have the most dead versions and when they were last vacuumedSELECT relname, n_live_tup, n_dead_tup,       last_autovacuum, last_autoanalyzeFROM pg_stat_user_tablesORDER BY n_dead_tup DESCLIMIT 10;

The progress of a running vacuum is shown by pg_stat_progress_vacuum, and since PostgreSQL 18, pg_stat_user_tables also has cumulative vacuum time: total_vacuum_time and total_autovacuum_time. To see autovacuum activity in the server log, set log_autovacuum_min_duration.

Since PostgreSQL 18, VACUUM and ANALYZE on a parent table also process its child tables; to process only the table itself, use VACUUM ONLY orders. Autovacuum does not analyse partitioned tables: after loading data, run ANALYZE on them manually.

Section sources

the section is written from these pages

Performance and EXPLAIN

A slow query is diagnosed from its plan: EXPLAIN shows how the planner intends to run it, and EXPLAIN ANALYZE runs the query and adds the actual time and row counts. What matters in a plan is whether the row estimates match reality and in which node the time goes.

How to read a plan

A query plan is a tree of nodes. At the bottom are the nodes that read tables: sequential scans, index scans, bitmap scans; above them are joins, sorts and aggregates. A node’s cost includes the cost of all its children.

sqlin psql
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
textexample output
                         QUERY PLAN------------------------------------------------------------- Seq Scan on orders  (cost=0.00..1887.00 rows=96 width=52)   Filter: (customer_id = 42)
ValueWhat it means
cost=0.00..1887.00The estimated cost to the first row and to the last row, in arbitrary units; by tradition, disk page reads
rows=96The estimated number of rows the node will return, not read
width=52The average row size in bytes
actual time=…With ANALYZE: the actual time in milliseconds to the first row and to the last row
loops=10How many times the node ran; time and rows are averages per run

Common plan nodes

NodeWhat it doesWhat to look at
Seq ScanReads the whole table sequentiallyRows Removed by Filter: how many of the rows read were discarded
Index ScanFinds rows through the index and reads them from the tableTypical for single rows and ORDER BY served by an index
Index Only ScanAnswers from the index without reading the tableHeap Fetches: how many times the table still had to be read
Bitmap Heap ScanCollects row addresses from the index, sorts them and reads the table in orderA middle ground between an index scan and a full scan
Nested LoopFor each row of the outer input, looks for matches in the inner oneloops of the inner node: how many times it ran
Hash JoinBuilds a hash table from one input and looks up rows of the other in itBatches greater than 1 on the Hash node: the hash table did not fit in memory
Merge JoinMerges two inputs sorted by the join keyNeeds a sort or an index on the key

EXPLAIN ANALYZE

EXPLAIN ANALYZE really runs the query and shows the actual actual time, rows and loops next to the estimates. Since PostgreSQL 18, the output also includes BUFFERS by default: how many pages were found in the shared cache (shared hit) and how many had to be read from outside it (read).

sqlin psql
BEGIN;EXPLAIN ANALYZEUPDATE orders SET status = 'paid' WHERE customer_id = 42;ROLLBACK;

What matters most in the output is whether the rows estimates are close to the actual counts. If they differ greatly, the planner chose a method for a different number of rows. If the table has recently changed a lot, update the statistics with ANALYZE orders without waiting for autovacuum.

A worked example: the plan before and after an index

A customer’s orders for the last month. COSTS OFF and TIMING OFF remove the estimates and per-node timings from the output so the plan is easier to read; the total query time remains. Without a suitable index, the server reads the whole table and discards what it does not need:

sqlin psql
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)SELECT id, total FROM ordersWHERE customer_id = 42  AND created_at >= now() - interval '30 days';
textwithout an index
 Seq Scan on orders (actual rows=11.00 loops=1)   Filter: ((customer_id = 42) AND (created_at >= ...))   Rows Removed by Filter: 99989   Buffers: shared hit=637 Planning Time: 0.120 ms Execution Time: 18.990 ms

A multicolumn index, with the equality column first and the range column second, leads straight to the right rows:

sqlin psql
CREATE INDEX orders_cust_created_idx    ON orders (customer_id, created_at);
textwith the index
 Index Scan using orders_cust_created_idx on orders (actual rows=11.00 loops=1)   Index Cond: ((customer_id = 42) AND (created_at >= ...))   Index Searches: 1   Buffers: shared hit=4 Planning Time: 0.210 ms Execution Time: 0.071 ms

In this example, execution time dropped from 19 to 0.07 ms, and the number of pages read from 637 to 4. For why an index is sometimes not used, see the section “Indexes”.

The heaviest queries: pg_stat_statements

The pg_stat_statements extension collects statistics on all of the server’s queries: how many times each ran and how much time it took in total and on average. The module is loaded at server start, so after editing postgresql.conf you need to restart, and then run CREATE EXTENSION in the database where you want to look at the statistics.

inipostgresql.conf
shared_preload_libraries = 'pg_stat_statements'compute_query_id = on
sqlin psql, after the restart
CREATE EXTENSION pg_stat_statements; SELECT calls,       round(total_exec_time::numeric) AS total_ms,       round(mean_exec_time::numeric, 1) AS mean_ms,       queryFROM pg_stat_statementsORDER BY total_exec_time DESCLIMIT 5;

Sorting by total_exec_time shows where the server spends the most time overall: a frequent fast query can rank above a rare slow one.

Server memory

ParameterWhat it affectsDefault
shared_buffersThe shared page cache. On a dedicated server with 1 GB of RAM or more, 25% of RAM is a reasonable start; more than 40% rarely helps128MB
work_memMemory for one sort or hash operation, beyond which it writes temporary files4MB
hash_mem_multiplierHow many times more than work_mem hash operations may use2.0
maintenance_work_memMemory for VACUUM, CREATE INDEX and ALTER TABLE ADD FOREIGN KEY64MB
sqlin psql
-- more memory for this session onlySET work_mem = '256MB';

Unused indexes

The idx_scan counter in pg_stat_user_indexes shows how many times an index has been used for lookups, and last_idx_scan shows when it was last used. Check any index with zero scans over a long period: it may not be needed.

sqlin psql
SELECT relname, indexrelname, idx_scan, last_idx_scanFROM pg_stat_user_indexesWHERE idx_scan = 0ORDER BY relname;

Section sources

the section is written from these pages

Replication and high availability

Streaming replication keeps a copy of the whole cluster on a second server. The primary sends it WAL records; the standby replays them and can answer read-only queries. Logical replication copies changes to individual tables through publications and subscriptions.

How streaming replication works

A standby connects to the primary, which sends it WAL records as they are generated, without waiting for a log file to fill. On the primary this appears as a walsender process, on the standby as walreceiver. By default replication is asynchronous: changes reach the standby with a small delay, usually under a second.

The standby reports how much WAL it has received, and the primary waits for this only in synchronous mode; a slot prevents the removal of WAL the standby has not yet received.

A standby that accepts read queries is called a hot standby. The whole cluster is replicated, and only between servers of the same major version; it is also best to keep minor versions identical, and when upgrading, to upgrade the standbys first.

Setting up a standby

  1. On the primary, create a replication role with the REPLICATION and LOGIN privileges and set a password for it. Any data can be extracted from the WAL stream, so grant REPLICATION only to a trusted role; it does not allow modifying data.
  2. Allow this role to connect in the primary’s pg_hba.conf: the database field takes the keyword replication. Check that max_wal_senders is large enough for all standbys.
  3. On the primary, create a replication slot for the new standby.
  4. On the standby, with PostgreSQL stopped, take a base backup of the primary into an empty data directory.
  5. In the standby’s data directory, create a standby.signal file, and in its postgresql.conf set primary_conninfo and primary_slot_name.
  6. Start the standby: when it sees standby.signal, it runs as a standby and receives WAL.
sqlin psql on the primary
CREATE ROLE replicator REPLICATION LOGIN;\password replicatorSELECT pg_create_physical_replication_slot('standby1');
inipg_hba.conf on the primary
# TYPE  DATABASE     USER        ADDRESS        METHODhost    replication  replicator  192.0.2.20/32  scram-sha-256
bashon the standby
# PGDATA is the empty data directory of the standbysudo -u postgres pg_basebackup \  -h 192.0.2.10 \  -U replicator \  -D "$PGDATA" \  -X stream \  -Psudo -u postgres touch "$PGDATA/standby.signal"
inipostgresql.conf on the standby
# application_name is the name used in synchronous_standby_namesprimary_conninfo = 'host=192.0.2.10 user=replicator application_name=standby1'primary_slot_name = 'standby1'

Keep the password for primary_conninfo in the ~/.pgpass file of the standby’s system user, with replication in the database field. pg_basebackup with the -R flag can also create standby.signal and write the connection settings; see the “Backup and recovery” section.

Replication slots

Without a slot, the primary may remove WAL segments before a lagging standby has received them, and the standby would have to be rebuilt from a new base backup. A replication slot prevents the primary from removing WAL until all standbys have received it, even if a standby is disconnected.

sqlon the primary
SELECT slot_name, slot_type, active FROM pg_replication_slots;

Synchronous replication

With asynchronous replication, a primary failure loses transactions that have not yet reached the standby. In synchronous mode, COMMIT waits until the standby has written the WAL to disk, and data is lost only if both servers fail at once. The price is response time: every COMMIT waits for at least a round trip to the standby.

inipostgresql.conf on the primary
# wait for an acknowledgement from at least one of the twosynchronous_standby_names = 'ANY 1 (standby1, standby2)'synchronous_commit = on
synchronous_commit valueWhat COMMIT waits forWhen data can be lost
remote_applyThe standby has replayed the transaction and it is visible to queries thereOnly if both servers fail
onThe standby has written the WAL to diskOnly if both servers fail
remote_writeThe standby has received the WAL and passed it to the OS, but has not yet written it to diskAn OS crash on the standby at the same time as a primary failure

You can change synchronous_commit for an individual session or transaction: confirm important changes synchronously and less valuable ones without waiting. If the synchronous standby goes down and the list has no replacement, COMMIT waits forever, so list more candidates in synchronous_standby_names than the number of confirmations you need.

Failing over to a standby

PostgreSQL does not detect a primary failure by itself and does not promote a standby; external tools are needed for that. A standby becomes the primary with the pg_ctl promote command or the pg_promote() function. When the old primary comes back, it must not run as a primary again, or both servers will accept writes; rebuild it as a standby, fastest with the pg_rewind utility.

bashon the standby
sudo -u postgres psql -c 'SELECT pg_promote();'

Monitoring and lag

On the primary, standbys are visible in pg_stat_replication. The state column changes from catchup to streaming once the standby has caught up, and sync_state shows whether it is synchronous. The difference between the current WAL position on the primary (pg_current_wal_lsn()) and the sent position (sent_lsn) is the WAL that has not yet gone to the standby: if it grows, the primary cannot send fast enough.

sqlon the primary
SELECT application_name, state, sync_state,       pg_current_wal_lsn() - sent_lsn AS unsent_bytes,       replay_lagFROM pg_stat_replication;

Logical replication

Logical replication transfers row changes rather than blocks, using a publish–subscribe model. You create a publication on the source server and a subscription on the receiving one. The current contents of the tables are copied first, then new changes arrive in the same order as on the source.

inipostgresql.conf on the source
wal_level = logical

A subscription connects to an ordinary database, so the source’s pg_hba.conf needs a line with the database name: host shop replicator 198.51.100.20/32 scram-sha-256.

sqlon the source server
-- the role needs read access for the initial copyGRANT SELECT ON orders, customers TO replicator;CREATE PUBLICATION shop_pub FOR TABLE orders, customers;
sqlon the receiving server
CREATE SUBSCRIPTION shop_sub    CONNECTION 'host=192.0.2.10 dbname=shop user=replicator'    PUBLICATION shop_pub;
AspectStreamingLogical
What it copiesThe whole server, byte for byteRow changes for selected tables
Server major versionsIdenticalCan differ
Writes on the copyNot allowed: read onlyAllowed, but writing to the same tables causes conflicts
Table schemaArrives with the dataCreated by hand
Typical useStandby server, offloading readsPart of the data to another database, merging several databases into one

For how to choose a way to move to a new major version, including through logical replication, see the “Versions and what’s new” section.

Section sources

the section is written from these pages

Backup and recovery

Backups are either logical or physical. pg_dump saves one database as SQL commands or an archive and is suitable for moving between versions. pg_basebackup, together with a WAL archive, copies the whole cluster and lets you restore it to any point in time (PITR).

MethodWhat it savesWhen to choose it
pg_dumpOne database: schema and data as of the start of the copyMoving a database, copying a single database, upgrading to a new major version
pg_dumpallAll databases in the cluster, roles and tablespacesA full logical copy of a small cluster
pg_basebackupThe files of the whole clusterThe basis for point-in-time recovery and for a standby server
WAL archiveAll changes after the base backupTogether with pg_basebackup, recovery to any point in time

Logical backups: pg_dump

pg_dump is an ordinary client: it works over the network and takes a consistent snapshot of the database as of the moment it starts. It does not interfere with the database; only commands that take an exclusive lock, such as most forms of ALTER TABLE, have to wait. It needs permission to read all the tables being copied, so a full backup is usually taken as a superuser.

FormatFlagRestore withNotes
SQL script-Fp, the defaultpsqlReadable text; can only be restored as a whole
Custom-Fcpg_restoreCompressed; individual tables can be restored
Directory-Fdpg_restoreA directory of files; the only format that allows a parallel dump with -j
bashon a machine with access to the database
export PGHOST=192.0.2.10 PGUSER=postgres# custom archive: compressed, can be restored selectivelypg_dump -Fc -f shop.dump shop# directory format, dumped by 4 parallel processespg_dump --format=directory \  --jobs=4 \  --file=shop_dir \  shop# roles and tablespaces of the whole clusterpg_dumpall --globals-only -f globals.sql

Before restoring, create an empty database from the template0 template. The roles that own objects or receive privileges must already exist, so load globals.sql first. After the restore, run ANALYZE so the planner has statistics.

bashrestoring an archive
psql -X -f globals.sql postgrescreatedb -T template0 shop_restoredpg_restore -d shop_restored -j 4 shop.dumppsql -d shop_restored -c 'ANALYZE;'

A dump in the form of an SQL script is loaded with psql. By default psql carries on after errors: ON_ERROR_STOP=on makes it stop at the first one, and -1 runs the whole file in a single transaction, so it is all or nothing.

bashrestoring a script
psql -X -1 \  --set ON_ERROR_STOP=on \  -d shop_restored \  -f shop.sql

Physical backup and WAL archive

The server always keeps a WAL. If you save every completed segment (usually 16 MB each) to an archive, a base backup can be rolled forward to any moment after it. This is point-in-time recovery (PITR). It works only for the whole cluster, and the archive needs a lot of space.

Enable archiving before the first base backup: recovery needs an unbroken chain of WAL from the start of the backup.

inipostgresql.conf
wal_level = replicaarchive_mode = onarchive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'

archive_mode can be changed only with a server restart. The archive command must return 0 only on success and must not overwrite existing files, which is what test ! -f does in the example. If archiving breaks, segments pile up in pg_wal. When the disk holding it fills up, the server shuts down abnormally: committed transactions are not lost, but the database will not work until space is freed. Monitor archiving through pg_stat_archiver.

bashon the backup server
pg_basebackup \  -h 192.0.2.10 \  -U replicator \  -D /backup/base-2026-10-31 \  -Ft \  -z \  -P

pg_basebackup connects using the replication protocol, so it needs a role with the REPLICATION privilege and a replication line in pg_hba.conf. By default (-X stream) it includes the WAL written while the backup was being taken. With the -R flag the backup is immediately ready to become a standby: pg_basebackup creates standby.signal in it and writes the connection settings to postgresql.auto.conf.

Point-in-time recovery

You can recover to any moment after the base backup ended. The server takes the backup and replays WAL from the archive up to the target, for example up to a minute before an erroneous DROP TABLE.

Segments after the recovery target are not replayed.
  1. Stop the server and, if there is enough space, copy its data directory, or at least pg_wal: it may hold segments that have not yet been archived.
  2. Clear the data directory and unpack the base backup into it, owned by the PostgreSQL system user rather than root.
  3. Delete the files in the backup’s pg_wal and put the saved unarchived segments there.
  4. Set restore_command and the recovery target in postgresql.conf, and create a recovery.signal file in the data directory.
  5. Start the server: it reads WAL from the archive up to the target. Check the data, and only then let users in.
inipostgresql.conf
restore_command = 'cp /mnt/archive/%f %p'recovery_target_time = '2026-10-31 14:59:00+05'recovery_target_action = 'promote'

By default, on reaching the target the server pauses recovery (recovery_target_action = 'pause') so that you can check the data, while promote opens it for work immediately. After recovery a new timeline begins, and its WAL does not overwrite the earlier archive segments.

Incremental backups

Since PostgreSQL 17, pg_basebackup --incremental takes the manifest of the previous backup and saves only the blocks changed since then; this requires WAL summarisation to be enabled on the server (summarize_wal = on). Such a backup cannot be restored directly: first pg_combinebackup assembles a full backup from it and the previous ones. So keep the whole chain together: without any one of the previous backups, an incremental backup is useless.

Verifying backups

Test archiving and recovery in advance, not on the day of an outage: restore a fresh backup on a separate server and check the data with queries.

basha trial restore
createdb -T template0 shop_checkpg_restore -d shop_check shop.dumppsql -d shop_check -c 'SELECT count(*) FROM orders;'

Section sources

the section is written from these pages

Security: roles, privileges and access

The main risks are a server exposed to the whole network, login without a password or with the obsolete MD5, and an application that runs as a superuser. Protection has two layers: pg_hba.conf decides who can connect and from where, and object privileges decide what a role can do in the database.

Roles and attributes

A role is both a user and a group. Only a role with the LOGIN attribute can connect to the server; CREATE USER is the same as CREATE ROLE with LOGIN. A superuser bypasses all privilege checks, so work under ordinary roles and give the application its own role with no special attributes.

AttributeWhat it grants
LOGINThe right to connect to the server
SUPERUSERBypasses all privilege checks except the right to log in
CREATEDBCreating databases
CREATEROLECreating roles and managing the ones the role created itself
REPLICATIONConnecting for streaming replication; needed together with LOGIN
CONNECTION LIMITThe cap on a role’s simultaneous connections; -1 means no limit
sqlin psql, as a superuser
-- application role: password login, no special privilegesCREATE ROLE app LOGIN CONNECTION LIMIT 50;\password app-- a read-only group and a member of itCREATE ROLE readonly NOLOGIN;CREATE ROLE analyst LOGIN;GRANT readonly TO analyst;

A role gets the privileges of all the groups it belongs to. Set a password with the psql command \password; PostgreSQL role passwords are unrelated to OS user passwords.

Object privileges

The creator of an object is its owner and can do anything with it; privileges for others are granted with GRANT and revoked with REVOKE. For a role to read a table, it needs CONNECT on the database (everyone has it by default through PUBLIC), USAGE on the schema and SELECT on the table. The special name PUBLIC means “all roles”.

sqlin the shop database
GRANT USAGE ON SCHEMA public TO readonly;GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;-- privileges on tables that app will create laterALTER DEFAULT PRIVILEGES FOR ROLE app IN SCHEMA public    GRANT SELECT ON TABLES TO readonly;

Default privileges for future objects are set with ALTER DEFAULT PRIVILEGES. Privileges on a table do not extend to the sequences behind its serial columns: grant those separately. The psql command \dp orders shows who has which privileges. For the CREATE privilege on the public schema, see the “Data model and types” section.

pg_hba.conf: who and from where

Each line of pg_hba.conf is a connection type, database, role, client address and authentication method. The server takes the first line that matches the type, address, database and role, and checks the login against that line only. If the check fails, later lines are not considered, and if no line matches, the login is denied.

FieldValues
Typelocal is a Unix socket; host is TCP/IP with or without SSL; hostssl is SSL only; hostnossl is non-SSL only
DatabaseA name, all, sameuser; replication is for physical replication connections
RoleA name, all, +group for all members of a group
Address192.0.2.0/24, ::1/128, a host name, samenet; local has no address
Methodscram-sha-256, peer, cert, reject, trust and others
MethodHow it authenticatesWhen to use it
scram-sha-256A password through a challenge–response scheme: the password is not sent, and the server stores a hashThe main method for network logins
peerThe client’s OS user name must match the roleLocal connections through a socket
certA client SSL certificateServices with issued certificates
rejectAlways refusesBlocking specific addresses before a general line
md5An MD5 or SCRAM password; MD5 is obsoleteOnly while migrating to SCRAM
trustLets anyone in under any role without checkingDo not use on servers
ininever do this
# anyone, from anywhere, without a passwordhost    all    all    0.0.0.0/0    trust
inipg_hba.conf
# TYPE  DATABASE  USER       ADDRESS          METHODlocal   all       postgres                    peerhostssl shop      app        192.0.2.0/24     scram-sha-256hostssl shop      +readonly  198.51.100.0/24  scram-sha-256

The order of lines matters: narrow rules first, then general ones. The pg_hba_file_rules view shows the file as it is on disk right now: after editing, check its error column and only then reload the configuration with SELECT pg_reload_conf();. SHOW hba_file; shows the path to the file.

sqlin psql, as a superuser
SELECT line_number, type, database, user_name, auth_method, errorFROM pg_hba_file_rules;

Passwords: SCRAM instead of MD5

scram-sha-256 prevents the password from being intercepted and stores a strong hash on the server. MD5 is no longer considered secure, and since PostgreSQL 18 MD5 passwords are deprecated: support for them will be removed in a future release. The password_encryption setting determines how a password is stored at the moment it is set.

Network access

By default the server accepts TCP connections only on localhost. To let clients in from the network, list the addresses of the interfaces you need in listen_addresses rather than opening all of them. Block the port for everyone else with a firewall; see the “Linux server hardening” reference, “Firewall” section.

inipostgresql.conf
listen_addresses = 'localhost,192.0.2.10'

hostssl lines allow only SSL connections; for this the ssl setting must be enabled on the server and a certificate issued. The client certificate is verified by the clientcert=verify-full option on a hostssl line. For how to issue certificates, see the “TLS and PKI” reference, “X.509 certificates” section.

Section sources

the section is written from these pages

Common errors and diagnostics

Start diagnosing with the server log: it describes the cause of a refusal in more detail than the message sent to the client. Then repeat the connection with psql, using the same address, port, role and database as the application; the text of the error will tell you at which step it occurs.

Order of checks

  1. The server is running and its log shows no FATAL at startup.
  2. The server listens on the right address and port.
  3. pg_hba.conf allows login from this address for this role and database.
  4. The role and database exist, and the password is correct.
  5. The role has privileges on the objects it needs.

Where the server log is

By default the server writes messages to stderr, and where they end up depends on how it was started. With logging_collector = on, the server writes log files itself into log_directory, which by default is log inside the data directory. With log_min_duration_statement, every query that takes longer than the given time is logged; analyse its plan using the “Performance and EXPLAIN” section.

inipostgresql.conf
logging_collector = onlog_directory = 'log'# log queries slower than 500 mslog_min_duration_statement = 500ms

Connection refused

Cause: nothing is listening on this address and port, either because the server is not running or because it accepts TCP only on localhost. This is not a refusal by access rules; that looks different. The full message: connection to server at "192.0.2.10", port 5432 failed: Connection refused.

bashon the database server
# does the server respond on this address and portpg_isready -h 192.0.2.10 -p 5432# which addresses the server listens onsudo -u postgres psql -c 'SHOW listen_addresses;'
  • The server is not running: start it, and read the log if it does not start.
  • The server listens only on localhost: add the address to listen_addresses and restart the server.
  • If instead of Connection refused the client waits and gets Connection timed out, the problem is the network or a firewall.

No such file or directory

Cause: the client connects through a Unix socket (no -h), and the server is not running or creates its socket in a different directory. The full message: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory. If the server is running, compare the directory in the message with the server’s unix_socket_directories setting.

bashon the database server
# does the server respond over TCP on this machinepg_isready -h localhost# connect over TCP, bypassing the socketpsql -h localhost -U app -d shop

no pg_hba.conf entry for host

Cause: the server received the connection, but pg_hba.conf has no line for this combination of address, role and database; all three are named in the message. Add a suitable line, reload the configuration and try again.

textserver message
FATAL:  no pg_hba.conf entry for host "192.0.2.7", user "app", database "shop"
sqlafter editing pg_hba.conf
SELECT pg_reload_conf();

password authentication failed for user

Cause: a line in pg_hba.conf matched, but the password check failed. Check the password and the method on that line; the server writes the exact reason the login was rejected to its own log.

sqlin psql, as a superuser
-- set a new password for the role\password app

role "app" does not exist

Cause: there is no such role in the cluster. Often the client did not pass -U, and psql used the OS user name. Specify the role explicitly or create it.

bashon the server
psql -U app -d shop# or create the role as postgressudo -u postgres createuser --pwprompt app

database "shop" does not exist

Cause: there is no database with that name, or no database name was given and the client substituted the role name: without -d, the default database is named after the role.

permission denied to create database

Cause: the role has no privilege to create databases. Create the database as a superuser and specify the owner, or give the role the CREATEDB attribute.

bashon the server
sudo -u postgres createdb --owner=app shop# or let the role create databases itselfsudo -u postgres psql -c 'ALTER ROLE app CREATEDB;'

could not create any TCP/IP sockets

Cause: the server cannot take the port at startup. If the line above says Address already in use, the port is already taken, most often by another PostgreSQL instance; Permission denied occurs when trying to take a reserved port.

textserver log
LOG:  could not bind IPv4 address "127.0.0.1": Address already in use...FATAL:  could not create any TCP/IP sockets
bashon the database server
# who is holding port 5432sudo ss -ltnp 'sport = :5432'

database is not accepting commands that assign new transaction IDs to avoid wraparound data loss

Cause: the transaction counter is nearly exhausted because VACUUM has not frozen old rows for a long time. Until vacuuming advances the counter, the database runs only read transactions. You do not need to stop the server or switch to single-user mode; proceed in this order:

  1. Finish or roll back old prepared transactions listed in pg_prepared_xacts.
  2. Finish long-open transactions: in pg_stat_activity, look for a large age(backend_xmin).
  3. Drop old replication slots from pg_replication_slots with a large age(xmin).
  4. Run VACUUM on the whole database as a superuser. Do not use VACUUM FULL or VACUUM FREEZE here.
  5. Once the database is working again, check the autovacuum settings.
sqlin psql
-- the closer the age is to 2 billion, the closer the limitSELECT datname, age(datfrozenxid) FROM pg_database;-- in the affected database, as a superuserVACUUM;

Section sources

the section is written from these pages

Versions and what’s new

This reference covers PostgreSQL 18. The latest release is 18.6, published on 13 August 2026. A new major version appears roughly once a year and is supported for 5 years, while minor releases with fixes come out at least every three months.

BranchStatusLatest releaseSupported until
18Supported, covered here18.614 November 2030
17Supported17.118 November 2029
16Supported16.159 November 2028
15Supported15.1911 November 2027
14Nearing end of support14.2412 November 2026

Branch 13 and older are no longer supported: the last 13 release was 13.23, and support ended on 13 November 2025. There was no 18.5: a regression was found after the build, so it was never released. The next major branch, 19, is not out yet: release candidate RC 1 appeared on 15 October 2026.

What changed in 18

  • Performance and EXPLAIN: the asynchronous I/O subsystem (the io_method parameter) speeds up sequential reads, bitmap scans and vacuuming; EXPLAIN ANALYZE now includes BUFFERS output automatically.
  • Indexes: a multicolumn B-tree can be used even without a condition on the first column, thanks to skip scan.
  • Data model and types: the uuidv7() function creates time-ordered UUIDs; generated columns are now virtual by default and computed at read time.
  • Security: the oauth authentication method in pg_hba.conf; CREATE ROLE and ALTER ROLE issue a warning when an MD5 password is set.
  • VACUUM and autovacuum: VACUUM and ANALYZE process inheritance child tables too, and only the parent with ONLY; the autovacuum_vacuum_max_threshold parameter caps the vacuum threshold for large tables.
  • Replication: inactive slots can be invalidated automatically with the idle_replication_slot_timeout parameter.

Deprecated and removed

  • MD5 passwords are deprecated and will be removed in a future major version; switch to scram-sha-256. To silence the warnings, set md5_password_warnings = off.
  • initdb now enables data checksums by default; --no-data-checksums turns them off. pg_upgrade requires the old and new clusters to have the same setting, so a cluster without checksums must be upgraded into a new one created with --no-data-checksums.
  • COPY FROM in CSV format no longer treats \. as the end of data, and \. must be alone on its line. Older psql clients may misbehave with \copy against a version 18 server.
  • UNLOGGED partitioned tables are no longer allowed.

Security updates

IdentifierWhat is affectedFixed in
CVE-2026-6471Logical decoding: a replication role could load any library as an output plugin. The permitted plugins are now listed in the output_plugin_libraries parameter18.6
CVE-2026-16239EXECUTE and FETCH: server memory disclosure and arbitrary code execution18.6
CVE-2026-14669, CVE-2026-14664Buffer overflow in to_char() and in regular expression functions18.6
CVE-2026-6464psql: data after a failed COPY ... FROM STDIN in a script was executed as SQL18.6
CVE-2026-14663pgcrypto: with an unsupported cipher, PGP data was left practically unencrypted18.6
CVE-2026-14681The server accepted a GSSAPI encryption request after a direct TLS connection, so pg_hba.conf rules that forbid TLS did not apply18.6
CVE-2026-18408psql: shell command injection through \unrestrict in a plain-text dump18.6
CVE-2026-6475pg_basebackup and pg_rewind: a malicious source could overwrite any accessible file18.4
CVE-2026-6479Server process crash when rejected SSL and GSS requests were interleaved18.4
CVE-2026-6473Integer overflows in memory size calculation: server crash and possible code execution18.4

How to upgrade

A minor release does not change the storage format: stop the server, install the new packages for the same branch and start it again, with no dump and restore. First read the Migration section of the release notes. In 18.6, for example, third-party logical decoding plugins must be added to output_plugin_libraries, and indexes of the btree_gist and ltree extensions may need to be rebuilt.

Major upgrade:

  1. Read the release notes for every major version between your current one and the new one, especially the Migration sections.
  2. Test your application on the new version installed alongside the old one.
  3. Choose a method. pg_upgrade converts the cluster in place in minutes, especially with --link; pg_dumpall and a restore into a new cluster take longer. Logical replication to a server of the new version allows a switchover in seconds.
  4. For pg_upgrade, first run the check with pg_upgrade --check, then the upgrade itself.
  5. Since PostgreSQL 18, pg_upgrade carries over planner statistics, except extended ones. Gather the missing ones after the upgrade: vacuumdb --all --analyze-in-stages --missing-stats-only.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “PostgreSQL” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61