PostgreSQL Cheat Sheet
This PostgreSQL cheat sheet covers 31 sections: psql meta-commands, data types, tables and constraints, SELECT, joins, CTEs, window functions, JSONB, arrays and ranges, MERGE and upserts, indexes, EXPLAIN ANALYZE, VACUUM, roles and row level security, pg_dump, replication and the SQLSTATE codes you will actually meet. Search it, filter it by your server version, copy any line with one click, and format, lint, lock check or convert a query without leaving the page.
By Bogdan SanduUpdated September 29, 2026
Checked against the PostgreSQL 18 documentation, with a preview of PostgreSQL 19, now in beta
Format, lint and check SQL
pg_dump, role and connection builders
Install & Connect
Install
Docker: a server in one command
The official image runs initdb on the first start only, using POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB; later starts ignore them because the data directory already exists. Pin the major version tag (postgres:18) so a pull never moves you to a new major release, which needs pg_upgrade or a dump and restore. From the 18 image on, the volume is mounted at /var/lib/postgresql rather than /var/lib/postgresql/data.
docker run -d --name pg -p 5432:5432 \
-e POSTGRES_PASSWORD=change-me -e POSTGRES_USER=app -e POSTGRES_DB=shop \
-v pgdata:/var/lib/postgresql postgres:18
docker exec -it pg psql -U app -d shop # psql inside the container
docker logs pg # first start runs initdb and the init scripts$ docker ps
CONTAINER ID IMAGE STATUS PORTS NAMES
9c1e0b7d4f2a postgres:18 Up 6 seconds 0.0.0.0:5432->5432/tcp pgDocker Compose with a health check
depends_on with service_healthy makes the application wait until PostgreSQL accepts connections, not merely until the container started. Files in docker-entrypoint-initdb.d, .sql or .sh, run once on the first start with an empty volume. From the 18 image on, PGDATA is /var/lib/postgresql/18/docker, so the volume mounts one level higher than in older images.
services:
db:
image: postgres:18
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: change-me
POSTGRES_DB: shop
ports: ["5432:5432"]
volumes:
- pgdata:/var/lib/postgresql # 18+: the parent directory, not .../data
- ./initdb:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app -d shop"]
interval: 5s
retries: 10
api:
depends_on:
db: { condition: service_healthy }
volumes:
pgdata:Linux, macOS and Windows
Distribution repositories often ship one older major version. The PostgreSQL Global Development Group (PGDG) repositories carry every supported release with the same packaging, so the version on your laptop can match production.
# Debian / Ubuntu: the PGDG repository has every supported major version
sudo apt install -y postgresql-common && sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
sudo apt install -y postgresql-18
# RHEL / Rocky / Alma: dnf install from download.postgresql.org, then
sudo /usr/pgsql-18/bin/postgresql-18-setup initdb && sudo systemctl enable --now postgresql-18
# macOS
brew install postgresql@18 && brew services start postgresql@18
# Windows: the EDB installer from postgresql.org, or winget install PostgreSQL.PostgreSQL.18Service control and where things live
sudo systemctl status postgresql # Debian names the unit postgresql@18-main
sudo pg_lsclusters # Debian: clusters, ports, data directories
sudo -u postgres psql -c 'SHOW data_directory;'
sudo -u postgres psql -c 'SHOW config_file;'
pg_ctl -D /var/lib/postgresql/18/main status # the low level tool behind the service
pg_ctl -D "$PGDATA" reload # re-read postgresql.conf and pg_hba.conf data_directory
-----------------------------
/var/lib/postgresql/18/main
(1 row)Connect
psql connections, from simplest to explicit
Without -h, psql connects through the local Unix socket, where pg_hba.conf usually allows peer authentication: the database role must match the operating system user, which is why sudo -u postgres works without a password. With -h it goes over TCP and the password or certificate rules apply. ON_ERROR_STOP and --single-transaction make a script stop at the first error and roll everything back instead of carrying on half applied.
sudo -u postgres psql # peer authentication as the postgres OS user
psql -h db.internal -p 5432 -U app -d shop
psql "postgresql://app@db.internal:5432/shop?sslmode=verify-full"
psql -h db.internal -U app -d shop -c 'SELECT version();'
psql -d shop -f migration.sql -v ON_ERROR_STOP=1 --single-transaction version
-------------------------------------------------------------
PostgreSQL 18.6 on x86_64-pc-linux-gnu, compiled by gcc ...
(1 row)Stop typing the password: .pgpass and service files
libpq, and so psql, pg_dump and most drivers built on it, looks up the password in ~/.pgpass (or %APPDATA%\postgresql\pgpass.conf on Windows) and ignores the file if other users can read it. That keeps passwords out of shell history and the process list, where PGPASSWORD and command line URLs can leak.
# ~/.pgpass, chmod 600, one line per server: host:port:database:user:password
db.internal:5432:shop:app:s3cret
*:5432:*:postgres:another-secret
# ~/.pg_service.conf, then: psql service=shop-prod
[shop-prod]
host=db.internal
port=5432
dbname=shop
user=app
sslmode=verify-full
export PGHOST=db.internal PGUSER=app PGDATABASE=shop # libpq reads these tooAllow remote connections: listen_addresses and pg_hba.conf
A connection is refused unless the server listens on that interface and a pg_hba.conf line matches the connection type, database, role and client address. The file is read top to bottom and the first match decides, so specific rules go first. pg_hba_file_rules shows the file as the server parsed it, including syntax errors, before you reload.
# postgresql.conf
listen_addresses = '*' # default 'localhost'; restart after changing
# pg_hba.conf, first matching line wins: type database user address method
local all postgres peer
host shop app 10.0.0.0/16 scram-sha-256
hostssl all all 0.0.0.0/0 scram-sha-256
host all all 0.0.0.0/0 reject
SELECT pg_reload_conf(); -- pg_hba.conf changes only need a reload
SELECT line_number, type, database, user_name, address, auth_method, error FROM pg_hba_file_rules; line_number | type | database | user_name | address | auth_method | error
-------------+---------+----------+------------+----------+---------------+-------
1 | local | {all} | {postgres} | | peer |
2 | host | {shop} | {app} | 10.0.0.0 | scram-sha-256 |
3 | hostssl | {all} | {all} | 0.0.0.0 | scram-sha-256 |
4 | host | {all} | {all} | 0.0.0.0 | reject |
(4 rows)Create a cluster by hand
A cluster is one data directory served by one postmaster, holding many databases. Choosing the encoding and locale provider at initdb time matters because they become the defaults for every database; the ICU provider gives the same collation results on every operating system, which libc locales do not.
initdb -D /data/pg18 --encoding=UTF8 --locale-provider=icu --icu-locale=en-US --auth-local=peer --auth-host=scram-sha-256
pg_ctl -D /data/pg18 -l /data/pg18/server.log start
initdb -D /data/pg18 --no-data-checksums # 18 enables checksums by default; opt out only to match an old cluster for pg_upgradepsql Commands
Find Your Way Around
List and describe objects
Every \d command is a query against the system catalogs that psql writes for you. Start psql with -E (or run \set ECHO_HIDDEN on) to print those queries, which is the quickest way to learn pg_catalog and to copy a catalog query into a monitoring script.
\l -- databases
\c shop -- connect to another database
\conninfo -- who and where you are connected
\dn -- schemas
\dt -- tables in the search_path
\dt billing.* -- tables in one schema
\d orders -- columns, indexes, constraints, triggers
\d+ orders -- plus storage, size, description
\di+ orders* -- indexes with sizes
\dv \dm \ds \df -- views, materialized views, sequences, functions
\du -- roles
\dx -- installed extensions
\dp orders -- privileges on a table Table "public.orders"
Column | Type | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+------------------------------
id | bigint | | not null | generated always as identity
customer_id | bigint | | not null |
status | text | | not null | 'new'::text
total | numeric(12,2) | | not null |
created_at | timestamp with time zone | | not null | now()
Indexes:
"orders_pkey" PRIMARY KEY, btree (id)
"orders_customer_id_created_at_idx" btree (customer_id, created_at)
Foreign-key constraints:
"orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)Help and leaving
\? -- every meta-command
\h CREATE INDEX -- SQL syntax for a statement
\h -- list of SQL commands
\q -- quit (Ctrl+D also works; exit and quit work since PostgreSQL 11)Output and Timing
Expanded rows, timing, null display
\x auto -- one column per line when the row is too wide
\timing on -- print how long each statement took
\pset null '(null)' -- make NULL visible
\pset linestyle unicode
\pset border 2
SELECT * FROM pg_stat_activity WHERE pid = pg_backend_pid() \gx -- \gx: expanded for one query-[ RECORD 1 ]----+-------------------------------
datname | shop
pid | 48213
usename | app
application_name | psql
state | active
query | SELECT * FROM pg_stat_activity ...Output to CSV, a file or a pager
\pset format csv
SELECT id, email FROM customers LIMIT 3;
\pset format aligned
\o /tmp/report.txt -- send output to a file
SELECT count(*) FROM orders;
\o -- back to the screen
psql -d shop --csv -c 'SELECT * FROM orders' > orders.csv -- from the shell
psql -d shop -At -c 'SELECT count(*) FROM orders' -- unaligned, tuples only: easy to scriptid,email
1,ana@example.com
2,radu@example.com
3,ioana@example.comScripting and Debugging in psql
Conditionals in psql scripts
\if, \elif, \else and \endif branch on a boolean psql variable, which \gset can fill from a query, so one deploy script can adapt to the database it runs against without a separate shell script.
SELECT count(*) > 0 AS has_orders FROM orders \gset
\if :has_orders
\echo 'orders exist, skipping seed'
\else
\i seed_orders.sql
\endif
psql -v ON_ERROR_STOP=1 -v env=staging -f deploy.sql -- pass variables from the shellWhy did that fail: \errverbose and \gdesc
SELECT * FROM ordrs;
\errverbose -- the last error with SQLSTATE and source location
SELECT id, total * 1.21 AS gross, created_at::date FROM orders \gdesc Column | Type
------------+---------
id | bigint
gross | numeric
created_at | date
(3 rows)\bind: extended protocol and parameters from psql
\bind sends the query with the extended query protocol, the way drivers do, so you can test parameterized statements, prepared statement plans and pooler behaviour from psql exactly as your application runs them.
SELECT * FROM orders WHERE customer_id = $1 AND status = $2 \bind 12 'paid' \gPivot a result with \crosstabview
SELECT country, date_trunc('month', created_at)::date AS month, sum(total)
FROM orders JOIN customers c ON c.id = orders.customer_id
GROUP BY 1, 2 ORDER BY 1, 2 \crosstabview country | 2026-07-01 | 2026-08-01 | 2026-09-01
---------+------------+------------+------------
DE | 4120.00 | 4880.50 | 5120.00
RO | 84290.00 | 86394.80 | 114165.60
(2 rows)Editing, Scripts and Variables
Edit, repeat, include
\e -- open the last query in $EDITOR, run it on save
\ef my_function -- edit a function definition
\sf my_function -- show a function definition
\i setup.sql -- run a file
\ir ../common.sql -- relative to the current script
\s -- history
\watch 2 -- re-run the last query every 2 secondsVariables, \gset and \gexec
psql substitutes :name before sending the query, :'name' as a properly quoted literal and :"name" as a quoted identifier, so values from \set or \gset never need manual escaping. \gexec runs every cell of the result as a statement, which turns a catalog query into a batch of maintenance commands.
\set customer_id 42
SELECT * FROM orders WHERE customer_id = :customer_id;
\set email 'ana@example.com'
SELECT * FROM customers WHERE email = :'email'; -- :'x' quotes as a literal
SELECT count(*) AS n FROM orders \gset
\echo :n orders
SELECT format('VACUUM (ANALYZE) %I.%I;', schemaname, relname)
FROM pg_stat_user_tables WHERE n_dead_tup > 100000 \gexec1284 ordersA sensible ~/.psqlrc
ON_ERROR_ROLLBACK interactive puts an implicit savepoint before each statement typed by hand, so a typo inside a long transaction does not abort everything you did before it, while scripts still fail normally.
\set QUIET 1
\pset null '(null)'
\x auto
\timing on
\set HISTSIZE 10000
\set HISTFILE ~/.psql_history- :DBNAME
\set ON_ERROR_ROLLBACK interactive
\set PROMPT1 '%n@%M/%/%R%# '
\unset QUIET\copy: load and export files from the client machine
\copy reads and writes files on the machine running psql and streams them through the connection, so it works on managed services and needs no special privileges. The SQL COPY command reads files on the database server itself, which needs superuser or the pg_read_server_files role.
\copy products (sku, name, price) FROM 'products.csv' WITH (FORMAT csv, HEADER true)
\copy (SELECT * FROM orders WHERE created_at >= '2026-09-01') TO 'september.csv' WITH (FORMAT csv, HEADER true)COPY 48213Databases & Schemas
Databases
Create, rename, drop
CREATE DATABASE copies a template, template1 by default, so anything installed there (extensions, functions) appears in every new database. template0 is the pristine copy and the only template that lets you choose a different encoding or locale. You cannot run CREATE or DROP DATABASE inside a transaction block.
CREATE DATABASE shop OWNER app ENCODING 'UTF8' TEMPLATE template0;
CREATE DATABASE shop_test TEMPLATE shop; -- fast copy; nobody may be connected to shop
ALTER DATABASE shop RENAME TO shop_old;
DROP DATABASE IF EXISTS shop_test;
DROP DATABASE shop_old WITH (FORCE); -- 13+: terminates its connections firstCREATE DATABASEICU collation for a new database
Indexes on text are sorted by the collation, so if the operating system's collation library changes its rules during an OS upgrade, those indexes can silently return wrong results. PostgreSQL records the collation version and warns on a mismatch; the fix is REINDEX followed by REFRESH COLLATION VERSION.
CREATE DATABASE shop_ro TEMPLATE template0 LOCALE_PROVIDER icu ICU_LOCALE 'ro-RO' ENCODING 'UTF8';
SELECT datname, datlocprovider, datcollate, datcollversion FROM pg_database;
ALTER DATABASE shop REFRESH COLLATION VERSION; -- after reindexing, when the library changed datname | datlocprovider | datcollate | datcollversion
----------+----------------+-------------+----------------
postgres | c | en_US.UTF-8 | 2.36
shop | c | en_US.UTF-8 | 2.36
shop_ro | i | en_US.UTF-8 | 153.120
(3 rows)Case and accent insensitive collations
A nondeterministic ICU collation compares strings by the rules you choose, here ignoring case (level2; level1 also ignores accents), so uniqueness and equality work the way users expect without lower() everywhere. LIKE on such columns works from 18; before that it raises an error, and pattern matching still uses the index less well than a plain collation.
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
CREATE TABLE members (email text COLLATE ci UNIQUE);
INSERT INTO members VALUES ('Ana@Example.com');
INSERT INTO members VALUES ('ana@example.com'); -- rejected: equal under ci
SELECT * FROM members WHERE email = 'ANA@EXAMPLE.COM'; -- foundERROR: duplicate key value violates unique constraint "members_email_key"
DETAIL: Key (email)=(ana@example.com) already exists.Per database settings and connection limits
ALTER DATABASE shop SET timezone = 'UTC';
ALTER DATABASE shop SET statement_timeout = '30s';
ALTER DATABASE shop CONNECTION LIMIT 200;
ALTER DATABASE shop_archive ALLOW_CONNECTIONS false; -- keep it, but nobody can connect
SELECT d.datname, s.setconfig FROM pg_db_role_setting s JOIN pg_database d ON d.oid = s.setdatabase; datname | setconfig
---------+--------------------------------------
shop | {timezone=UTC,statement_timeout=30s}
(1 row)Schemas and search_path
Namespaces inside a database
Unqualified names are looked up along search_path, starting with a schema named after the current role if one exists. Since PostgreSQL 15 ordinary users can no longer create objects in the public schema by default, which is why a fresh application role often fails with permission denied for schema public until it gets its own schema or a GRANT CREATE.
CREATE SCHEMA billing AUTHORIZATION app;
CREATE TABLE billing.invoices (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, total numeric(12,2));
SHOW search_path;
SET search_path TO billing, public; -- this session
ALTER ROLE app SET search_path = billing, public; -- every new session of app
ALTER SCHEMA billing RENAME TO finance;
DROP SCHEMA finance CASCADE; -- and everything in it search_path
-----------------
"$user", public
(1 row)Sizes of databases, schemas and tables
SELECT datname, pg_size_pretty(pg_database_size(datname)) AS size FROM pg_database ORDER BY pg_database_size(datname) DESC;
SELECT relname AS table,
pg_size_pretty(pg_total_relation_size(relid)) AS total,
pg_size_pretty(pg_relation_size(relid)) AS heap,
pg_size_pretty(pg_indexes_size(relid)) AS indexes
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC LIMIT 5; table | total | heap | indexes
-------------+---------+---------+---------
order_items | 1804 MB | 1210 MB | 590 MB
orders | 912 MB | 604 MB | 306 MB
events | 377 MB | 330 MB | 46 MB
(3 rows)What is in this database
information_schema is the SQL standard view of the catalog and is portable across databases; pg_catalog is PostgreSQL's own and shows everything, including partitioned tables (relkind p), materialized views and storage details. Most \d commands in psql read pg_catalog.
SELECT table_schema, table_name, table_type FROM information_schema.tables
WHERE table_schema NOT IN ('pg_catalog', 'information_schema') ORDER BY 1, 2;
SELECT n.nspname AS schema, count(*) AS tables
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'p') AND n.nspname NOT LIKE 'pg\_%' AND n.nspname <> 'information_schema'
GROUP BY 1 ORDER BY 2 DESC;Data Types
Numbers and Text
Pick the smallest type that is certainly big enough
| Type | Range or size | Use it for |
|---|---|---|
smallint | -32768 to 32767 | small counters, years |
integer | about 2.1 billion | most counts |
bigint | about 9.2 quintillion | primary keys, anything that grows |
numeric(12,2) | exact decimal | money, quantities that must add up |
double precision | 15 digits, approximate | measurements, science |
text | unlimited | almost every string |
varchar(n) | up to n characters | when a length limit is a real rule |
boolean | true, false, null | flags |
Exact versus approximate arithmetic
numeric stores decimal digits exactly, so sums of prices always add up, at the cost of slower arithmetic; float8 is fast binary floating point that cannot represent 0.1 exactly. Integer division truncates in PostgreSQL, so 7 / 2 is 3; make one side numeric when you want a fraction.
SELECT 0.1::float8 + 0.2::float8 AS float_sum, 0.1::numeric + 0.2::numeric AS numeric_sum;
SELECT 7 / 2 AS int_div, 7 / 2.0 AS num_div, 7 % 2 AS remainder;
SELECT round(2.675::numeric, 2), round(2.675::float8::numeric, 2); float_sum | numeric_sum
---------------------+-------------
0.30000000000000004 | 0.3
(1 row)text versus varchar versus char
In PostgreSQL text, varchar(n) and varchar are the same storage and speed; the only difference is the length check. A CHECK constraint is easier to change later than a varchar(n) column type. char(n) pads with spaces and trims them in comparisons, which surprises nearly everyone, so avoid it.
CREATE TABLE people (
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 200),
code varchar(3),
flag char(2)
);
SELECT 'ab'::char(4) || '|' AS padded, length('ab'::char(4)) AS len;Dates and Times
timestamptz is almost always the right choice
timestamptz does not store a time zone: it stores an absolute instant in UTC and converts to the session's TimeZone on output. timestamp without time zone stores a wall clock reading with no zone at all, so the same value means different instants for users in different countries. Store instants as timestamptz and keep the user's zone in its own column if you need it.
SELECT now(), now()::date, current_time, localtimestamp;
SET timezone = 'Europe/Bucharest';
SELECT '2026-09-29 10:00:00+00'::timestamptz; -- shown in the session time zone
SELECT '2026-09-29 10:00:00'::timestamp AT TIME ZONE 'UTC'; -- timestamp to timestamptz
SELECT now() AT TIME ZONE 'America/New_York'; -- timestamptz to local wall clock timestamptz
------------------------
2026-09-29 13:00:00+03
(1 row)Intervals and date arithmetic
SELECT now() + interval '7 days', now() - interval '1 month 2 hours';
SELECT '2026-09-29'::date - '2026-01-01'::date AS days_between; -- integer
SELECT age('2026-09-29', '1990-03-14'); -- years mons days
SELECT date_trunc('month', now()), date_trunc('week', now());
SELECT extract(epoch FROM interval '2 hours 30 minutes'); -- seconds
SELECT make_date(2026, 9, 29), make_interval(days => 10); days_between
--------------
271
(1 row)UUIDs, Enums, Domains and More
UUID keys: random or time ordered
Random version 4 UUIDs scatter inserts across the whole primary key index, so every insert touches a different page and the index grows fragmented. UUIDv7 starts with a millisecond timestamp, so new keys land at the end of the index like a bigint sequence would, while still being globally unique and safe to generate in the application.
SELECT gen_random_uuid(); -- version 4, built in since 13
SELECT uuidv7(); -- 18+: time ordered, friendlier to B-tree indexes
SELECT uuid_extract_timestamp(uuidv7());
CREATE TABLE events (id uuid PRIMARY KEY DEFAULT uuidv7(), payload jsonb); uuidv7
--------------------------------------
019989a2-6f3b-7c1e-9a4d-2f6b0c5e8d11
(1 row)Enums and domains
An enum is compact and ordered, and adding values is cheap, but removing or renaming one is awkward; a text column with a CHECK constraint or a small lookup table is easier to evolve. A domain attaches a rule to a type once, so every column declared with it enforces the same check.
CREATE TYPE order_status AS ENUM ('new', 'paid', 'shipped', 'refunded');
ALTER TYPE order_status ADD VALUE 'cancelled' AFTER 'paid';
SELECT enum_range(NULL::order_status);
CREATE DOMAIN email AS text CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$');
CREATE TABLE subscribers (address email NOT NULL);Identity columns instead of serial
Identity columns are the SQL standard replacement for serial: the sequence belongs to the column, permissions follow the table, and GENERATED ALWAYS stops the application from inserting its own ids by accident. After a bulk load with explicit ids, move the sequence past the highest value or the next insert fails with a duplicate key.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
INSERT INTO customers (name) VALUES ('Ana') RETURNING id;
INSERT INTO customers (id, name) OVERRIDING SYSTEM VALUE VALUES (1000, 'Imported');
SELECT setval(pg_get_serial_sequence('customers', 'id'), (SELECT max(id) FROM customers)); id
----
1
(1 row)Types people forget PostgreSQL has
SELECT '192.168.1.20'::inet << '192.168.1.0/24'::cidr AS in_subnet;
SELECT '\xdeadbeef'::bytea, md5('hello'), sha256('hello'::bytea);
SELECT 'fat & rat'::tsquery, '[2026-09-01,2026-10-01)'::daterange;
SELECT '(1,2)'::point <-> '(4,6)'::point AS distance; in_subnet
-----------
t
(1 row)Tables & Constraints
Create Tables
A table with the constraints you will actually want
PostgreSQL does not index foreign key columns automatically, only the referenced primary key. Without an index on orders.customer_id, deleting a customer or joining from customers to orders scans the whole orders table, so add one for almost every foreign key.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id) ON DELETE RESTRICT,
status text NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'paid', 'shipped', 'refunded')),
total numeric(12,2) NOT NULL CHECK (total >= 0),
email text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (customer_id, created_at)
);
CREATE INDEX ON orders (customer_id);
COMMENT ON TABLE orders IS 'One row per checkout';INSERT INTO orders (customer_id, status, total, email) VALUES (1, 'lost', 10, 'a@b.c');
ERROR: new row for relation "orders" violates check constraint "orders_status_check"
DETAIL: Failing row contains (7, 1, lost, 10.00, a@b.c, 2026-09-29 10:14:02.118+00).Generated columns, virtual by default in 18
A STORED generated column is computed on write and takes disk space, and it can be indexed. PostgreSQL 18 adds VIRTUAL columns, computed when read, and makes VIRTUAL the default when you write neither keyword. Before 18 only STORED exists, so spell it out if the schema must also work on older servers.
CREATE TABLE line_items (
qty integer NOT NULL,
unit_price numeric(10,2) NOT NULL,
amount numeric(12,2) GENERATED ALWAYS AS (qty * unit_price) VIRTUAL,
search tsvector GENERATED ALWAYS AS (to_tsvector('english', coalesce(note, ''))) STORED,
note text
);Exclusion constraints: no overlapping bookings
A unique constraint can only forbid equal values; an exclusion constraint forbids any pair of rows for which all listed operators return true, here the same room and overlapping time ranges. It is enforced by the database under concurrency, which application code checking first and inserting second cannot guarantee.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
room_id integer NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
INSERT INTO bookings VALUES (1, '[2026-10-01 14:00, 2026-10-03 11:00)');
INSERT INTO bookings VALUES (1, '[2026-10-02 14:00, 2026-10-04 11:00)');ERROR: conflicting key value violates exclusion constraint "bookings_room_id_during_excl"
DETAIL: Key (room_id, during)=(1, ["2026-10-02 14:00:00+00","2026-10-04 11:00:00+00")) conflicts with existing key (room_id, during)=(1, ["2026-10-01 14:00:00+00","2026-10-03 11:00:00+00")).Temporal primary keys, 18+
WITHOUT OVERLAPS turns the last key column into a range that may not overlap for the same other key values, so a price list can keep its history in one table. PERIOD foreign keys check that the referenced ranges cover the referencing range. Both need the btree_gist extension for the scalar columns.
CREATE TABLE prices (
sku text NOT NULL,
valid daterange NOT NULL,
price numeric(10,2) NOT NULL,
PRIMARY KEY (sku, valid WITHOUT OVERLAPS)
);
CREATE TABLE price_refs (
sku text, valid daterange,
FOREIGN KEY (sku, PERIOD valid) REFERENCES prices (sku, PERIOD valid)
);UNIQUE NULLS NOT DISTINCT
By default a unique constraint treats NULLs as distinct, so any number of rows with a NULL in a key column are allowed, which is rarely what a rule like one welcome coupon per customer or guest means. NULLS NOT DISTINCT, added in 15, treats NULLs as equal; on 14 a partial unique index WHERE customer_id IS NULL does the same job.
CREATE TABLE coupons (code text, customer_id bigint, UNIQUE NULLS NOT DISTINCT (code, customer_id));
INSERT INTO coupons VALUES ('WELCOME', NULL);
INSERT INTO coupons VALUES ('WELCOME', NULL); -- rejected from 15 with NULLS NOT DISTINCTERROR: duplicate key value violates unique constraint "coupons_code_customer_id_key"
DETAIL: Key (code, customer_id)=(WELCOME, null) already exists.Temporary, unlogged and copied tables
CREATE TEMP TABLE staging (LIKE products INCLUDING DEFAULTS); -- gone at the end of the session
CREATE UNLOGGED TABLE import_buffer (line text); -- fast, not crash safe, not replicated
CREATE TABLE orders_archive (LIKE orders INCLUDING ALL); -- columns, defaults, constraints, indexes
CREATE TABLE top_customers AS SELECT customer_id, sum(total) FROM orders GROUP BY 1;Sequences
Sequences and identity values
nextval is never rolled back, so a failed or rolled back INSERT leaves a gap, and sequences with CACHE hand out blocks per session; never rely on ids being consecutive. For gapless numbers such as legal invoice numbers, use a counter row updated inside the same transaction, accepting that it serializes those inserts.
CREATE SEQUENCE invoice_no START 1000 INCREMENT 1;
SELECT nextval('invoice_no'), currval('invoice_no');
SELECT setval('invoice_no', 5000); -- next value is 5001
ALTER TABLE customers ALTER COLUMN id RESTART WITH 1000; -- identity columns
SELECT sequencename, last_value, increment_by FROM pg_sequences; sequencename | last_value | increment_by
------------------+------------+--------------
customers_id_seq | | 1
invoice_no | 5000 | 1
(2 rows)Change Tables Without an Outage
Common ALTER TABLE forms
ALTER TABLE orders ADD COLUMN note text;
ALTER TABLE orders ADD COLUMN source text NOT NULL DEFAULT 'web'; -- instant since 11
ALTER TABLE orders RENAME COLUMN note TO customer_note;
ALTER TABLE orders ALTER COLUMN customer_note TYPE varchar(500);
ALTER TABLE orders ALTER COLUMN source DROP DEFAULT;
ALTER TABLE orders ALTER COLUMN email SET NOT NULL;
ALTER TABLE orders DROP COLUMN IF EXISTS legacy_flag;
ALTER TABLE orders RENAME TO purchases;Add constraints on a big table without a long lock
Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock, and while one waits for a long running query to finish, every other query on the table queues behind it, which looks like an outage. lock_timeout makes the ALTER give up and retry later. NOT VALID adds the constraint for new rows at once, and VALIDATE CONSTRAINT checks old rows under a lighter lock.
SET lock_timeout = '3s'; -- give up instead of queueing everyone behind you
ALTER TABLE orders ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk; -- scans, but lets reads and writes continue
ALTER TABLE orders ADD CONSTRAINT orders_email_nn CHECK (email IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_email_nn;
ALTER TABLE orders ALTER COLUMN email SET NOT NULL; -- 12+: uses the validated check, no scan
ALTER TABLE orders DROP CONSTRAINT orders_email_nn;ERROR: canceling statement due to lock timeoutWhich changes rewrite the whole table
| Change | Rewrite? | Notes |
|---|---|---|
ADD COLUMN with no default or a constant default | no | metadata only since 11 |
ADD COLUMN ... DEFAULT now() | no | now() is stable: evaluated once, stored as metadata |
ADD COLUMN ... DEFAULT random(), gen_random_uuid(), clock_timestamp() | yes | volatile defaults are evaluated per row |
ADD COLUMN identity or GENERATED ... STORED | yes | every existing row gets a value |
ALTER COLUMN TYPE varchar(50) to varchar(100) or text | no | widening needs no rewrite |
ALTER COLUMN TYPE int to bigint | yes | plus every index on the column |
SET NOT NULL | scan, no rewrite | skipped if a validated CHECK proves it |
DROP COLUMN | no | the space is reclaimed by later updates or VACUUM FULL |
ALTER TABLE ... SET TABLESPACE | yes | copies every page |
SELECT & Filtering
The Basics
Filter, sort, limit
Without ORDER BY, PostgreSQL returns rows in whatever order the plan produces, which can change between runs, so LIMIT without ORDER BY is a random sample in disguise. NULLs sort last in ascending order and first in descending order unless you say NULLS FIRST or NULLS LAST.
SELECT id, name, email
FROM customers
WHERE country = 'RO' AND created_at >= '2026-01-01'
ORDER BY created_at DESC NULLS LAST, id
LIMIT 20 OFFSET 40;
SELECT * FROM products ORDER BY price DESC FETCH FIRST 3 ROWS WITH TIES; -- standard form, keeps ties id | name | email
-----+------+------------------
812 | Ana | ana@example.com
804 | Radu | radu@example.com
(2 rows)Every WHERE operator you will use
WHERE price BETWEEN 10 AND 50 -- inclusive at both ends
WHERE status IN ('paid', 'shipped')
WHERE id = ANY ('{3,7,9}'::bigint[]) -- one array parameter instead of a long IN list
WHERE name ILIKE 'an%' -- case insensitive LIKE
WHERE sku ~ '^OAK-[0-9]+$' -- POSIX regex; ~* ignores case, !~ negates
WHERE email IS NULL
WHERE shipped_at IS DISTINCT FROM delivered_at -- NULL aware inequality
WHERE (country, city) = ('RO', 'Cluj') -- row comparisonNULL rules that trip people up
Any comparison with NULL returns NULL, not false, and WHERE keeps only rows where the condition is true. So coupon <> 'SUMMER' silently drops every row where coupon is NULL; write coupon IS DISTINCT FROM 'SUMMER' when those rows should count.
SELECT NULL = NULL AS eq, NULL IS NULL AS is_null, NULL IS NOT DISTINCT FROM NULL AS same;
SELECT coalesce(phone, email, 'no contact') FROM customers;
SELECT nullif(discount, 0) FROM orders; -- 0 becomes NULL, avoids division by zero
SELECT count(*) FROM orders WHERE coupon <> 'SUMMER'; -- rows with a NULL coupon are not counted eq | is_null | same
----+---------+------
| t | t
(1 row)Pagination Two Ways
OFFSET: simple, and slower on every page
OFFSET still reads and discards every skipped row, so page 2001 does two thousand times the work of page 1, and rows inserted between requests shift the pages under the user. It is fine for small tables and admin screens with page numbers.
SELECT id, created_at, total FROM orders
ORDER BY created_at DESC, id DESC
LIMIT 50 OFFSET 100000; -- page 2001 Limit (actual time=182.4..182.5 rows=50 loops=1)
-> Index Scan using orders_created_id_idx on orders (actual time=0.03..176.2 rows=100050 loops=1)Keyset: remember the last row, ask for the next ones
With an index matching the sort order, every page is a short index scan that starts where the previous one stopped, so the thousandth page costs the same as the first. The row comparison keeps rows with equal created_at in a stable order; the trade off is no jumping to page 2001, only next and previous.
SELECT id, created_at, total FROM orders
WHERE (created_at, id) < ('2026-09-20 08:15:00+00', 10480) -- last row of the previous page
ORDER BY created_at DESC, id DESC
LIMIT 50;
CREATE INDEX CONCURRENTLY orders_created_id_idx ON orders (created_at DESC, id DESC); Limit (actual time=0.04..0.09 rows=50 loops=1)
-> Index Scan using orders_created_id_idx on orders (actual time=0.03..0.08 rows=50 loops=1)
Index Cond: (ROW(created_at, id) < ROW('2026-09-20 08:15:00+00'::timestamp with time zone, 10480))PostgreSQL Favourites
DISTINCT ON: the first row of each group
DISTINCT ON keeps the first row for each distinct value of its expressions, in the order given by ORDER BY, which must start with the same expressions. It is the shortest way to write latest row per group in PostgreSQL, and with an index on (customer_id, created_at DESC) it is fast too.
SELECT DISTINCT ON (customer_id) customer_id, id, total, created_at
FROM orders
ORDER BY customer_id, created_at DESC; -- latest order per customer customer_id | id | total | created_at
-------------+-------+--------+------------------------
12 | 10060 | 410.00 | 2026-09-28 17:02:44+00
15 | 10049 | 199.00 | 2026-09-19 11:40:02+00
(2 rows)CASE, and FILTER instead of CASE inside aggregates
SELECT id,
CASE WHEN total >= 500 THEN 'large'
WHEN total >= 100 THEN 'medium'
ELSE 'small' END AS size
FROM orders;
SELECT count(*) FILTER (WHERE status = 'paid') AS paid,
count(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders; paid | refunded
------+----------
311 | 27
(1 row)Random samples without sorting the table
SELECT * FROM events TABLESAMPLE SYSTEM (1); -- about 1% of pages, very fast
SELECT * FROM events TABLESAMPLE BERNOULLI (1) REPEATABLE (42); -- about 1% of rows, reproducible
SELECT * FROM products ORDER BY random() LIMIT 5; -- fine for small tables onlyInline data with VALUES
SELECT * FROM (VALUES (1, 'RO'), (2, 'DE'), (3, 'FR')) AS t(id, country);
SELECT o.* FROM orders o JOIN (VALUES (10042), (10049)) AS pick(id) USING (id); id | country
----+---------
1 | RO
2 | DE
3 | FR
(3 rows)Joins
The Same Two Tables, Four Joins
INNER JOIN: rows that match on both sides
SELECT c.name, o.id AS order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.name, o.id; name | order_id | total
------+----------+--------
Ana | 10042 | 249.50
Ana | 10051 | 25.25
Radu | 10049 | 199.00
(3 rows)LEFT JOIN: every customer, orders when there are some
A condition on the right table belongs in ON when you want to keep unmatched left rows. Put o.status = 'paid' in WHERE instead and the NULL rows for customers without paid orders are filtered out, silently turning the LEFT JOIN into an inner join.
SELECT c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
ORDER BY c.name; name | order_id | total
-------+----------+--------
Ana | 10042 | 249.50
Ioana | |
Radu | 10049 | 199.00
(3 rows)Anti join: customers who never ordered
NOT EXISTS is planned as an anti join and is safe with NULLs. NOT IN (SELECT customer_id FROM orders) returns no rows at all as soon as one customer_id in orders is NULL, because x NOT IN (..., NULL) is never true.
SELECT c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id); name
-------
Ioana
(1 row)FULL OUTER JOIN: everything from both sides
SELECT coalesce(a.sku, b.sku) AS sku, a.qty AS warehouse, b.qty AS shop
FROM stock_warehouse a
FULL JOIN stock_shop b ON b.sku = a.sku; sku | warehouse | shop
-------+-----------+------
OAK-1 | 12 | 3
ASH-4 | 5 |
ELM-2 | | 7
(3 rows)LATERAL and Other Shapes
LATERAL: the top 3 orders per customer
A LATERAL subquery can refer to columns of the tables before it, so it runs once per outer row, like a correlated subquery that returns several columns and rows. With an index on (customer_id, total DESC) each run is a short index scan, which beats ranking the whole orders table with a window function when customers have many orders.
SELECT c.name, t.id, t.total
FROM customers c
CROSS JOIN LATERAL (
SELECT o.id, o.total FROM orders o
WHERE o.customer_id = c.id
ORDER BY o.total DESC LIMIT 3
) t;USING, self joins, several tables
SELECT * FROM order_items JOIN order_notes USING (order_id); -- one output column for order_id
SELECT e.name AS employee, m.name AS manager
FROM staff e LEFT JOIN staff m ON m.id = e.manager_id; -- self join
SELECT o.id, c.name, p.name AS product
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id;Combine result sets
SELECT email FROM customers UNION SELECT email FROM newsletter; -- distinct rows
SELECT email FROM customers UNION ALL SELECT email FROM newsletter; -- keeps duplicates, faster
SELECT email FROM customers INTERSECT SELECT email FROM newsletter; -- in both
SELECT email FROM customers EXCEPT SELECT email FROM newsletter; -- in the first only email
------------------
ana@example.com
radu@example.com
(2 rows)Semi join and join with an array column
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.total > 500);
SELECT p.name, t.tag FROM products p CROSS JOIN LATERAL unnest(p.tags) AS t(tag);
SELECT p.* FROM products p JOIN tags t ON t.name = ANY (p.tags);Aggregates
Group and Aggregate
GROUP BY with HAVING
WHERE filters rows before grouping, HAVING filters groups after aggregation, so conditions on plain columns belong in WHERE where they can use an index. PostgreSQL lets you GROUP BY a primary key and select the other columns of that table without listing them, because they are functionally dependent on it.
SELECT status, count(*) AS orders, round(avg(total), 2) AS avg_total, sum(total) AS revenue
FROM orders
WHERE created_at >= date_trunc('month', now())
GROUP BY status
HAVING count(*) > 10
ORDER BY revenue DESC; status | orders | avg_total | revenue
----------+--------+-----------+----------
shipped | 1284 | 75.09 | 96412.50
paid | 311 | 73.55 | 22873.10
refunded | 27 | 70.52 | 1904.00
(3 rows)count variants and NULLs
SELECT count(*) AS rows, count(phone) AS with_phone, count(DISTINCT country) AS countries FROM customers;
SELECT coalesce(sum(total), 0) FROM orders WHERE customer_id = 999; -- sum of no rows is NULL rows | with_phone | countries
--------+------------+-----------
210044 | 162310 | 31
(1 row)Strings, arrays and JSON from groups
SELECT o.customer_id,
string_agg(DISTINCT i.sku, ', ' ORDER BY i.sku) AS skus,
array_agg(DISTINCT o.status) AS statuses,
jsonb_agg(DISTINCT jsonb_build_object('id', o.id, 'total', o.total)) AS orders
FROM orders o JOIN order_items i ON i.order_id = o.id
GROUP BY o.customer_id; customer_id | skus | statuses
-------------+--------------+----------------
12 | ASH-4, OAK-1 | {paid,shipped}
(1 row)Beyond the Basics
Subtotals and a grand total in one query
ROLLUP (a, b) produces the groups (a, b), (a) and () in one pass, CUBE produces every combination, and GROUPING SETS lists exactly the ones you want. grouping() tells a subtotal row from a real NULL in the data.
SELECT country, status, sum(total) AS revenue, grouping(country, status) AS level
FROM orders JOIN customers c ON c.id = orders.customer_id
GROUP BY ROLLUP (country, status)
ORDER BY country NULLS LAST, status NULLS LAST; country | status | revenue | level
---------+---------+-----------+-------
DE | paid | 5120.00 | 0
DE | | 5120.00 | 1
RO | paid | 17753.10 | 0
RO | shipped | 96412.50 | 0
RO | | 114165.60 | 1
| | 119285.60 | 3
(6 rows)Median, percentiles, mode
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY total) AS median,
percentile_cont(ARRAY[0.9, 0.99]) WITHIN GROUP (ORDER BY total) AS p90_p99,
percentile_disc(0.5) WITHIN GROUP (ORDER BY total) AS median_actual_value,
mode() WITHIN GROUP (ORDER BY status) AS most_common_status
FROM orders; median | p90_p99 | median_actual_value | most_common_status
--------+----------------+---------------------+--------------------
74 | {199.5,412.25} | 74.00 | shipped
(1 row)Fill the gaps: days with no orders
SELECT d::date AS day, count(o.id) AS orders
FROM generate_series('2026-09-01'::date, '2026-09-03', interval '1 day') AS d
LEFT JOIN orders o ON o.created_at >= d AND o.created_at < d + interval '1 day'
GROUP BY d ORDER BY d; day | orders
------------+--------
2026-09-01 | 41
2026-09-02 | 0
2026-09-03 | 38
(3 rows)any_value, bool_and and friends
any_value, new in 16, returns an arbitrary value from the group, for columns you know are identical within it but cannot prove to the planner. On older versions min() does the same job.
SELECT customer_id, any_value(email) AS email, bool_and(paid) AS all_paid, bool_or(refunded) AS any_refund,
min(created_at), max(created_at)
FROM orders GROUP BY customer_id;Subqueries & CTEs
Subqueries
Scalar, list, derived table, correlated
SELECT name, (SELECT count(*) FROM orders o WHERE o.customer_id = c.id) AS orders FROM customers c;
SELECT * FROM products WHERE price > (SELECT avg(price) FROM products);
SELECT * FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE total > 500);
SELECT avg(n) FROM (SELECT customer_id, count(*) AS n FROM orders GROUP BY 1) per_customer;ANY and ALL
SELECT * FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'chairs');
SELECT * FROM orders WHERE status = ANY (ARRAY['paid', 'shipped']);
SELECT * FROM customers WHERE email ILIKE ANY (ARRAY['%@gmail.com', '%@yahoo.com']);Common Table Expressions
WITH: name the steps
Since PostgreSQL 12, a CTE that is referenced once and has no side effects is inlined into the main query, so the planner can push filters into it. Write WITH x AS MATERIALIZED (...) to force the old behaviour of computing it once, or NOT MATERIALIZED to force inlining of a CTE used several times.
WITH monthly AS (
SELECT date_trunc('month', created_at) AS month, sum(total) AS revenue
FROM orders GROUP BY 1
)
SELECT month, revenue, revenue - lag(revenue) OVER (ORDER BY month) AS change
FROM monthly ORDER BY month; month | revenue | change
------------------------+-----------+----------
2026-07-01 00:00:00+00 | 88410.00 |
2026-08-01 00:00:00+00 | 91275.30 | 2865.30
2026-09-01 00:00:00+00 | 121189.60 | 29914.30
(3 rows)Recursive CTE: walk a tree
WITH RECURSIVE tree AS (
SELECT id, name, parent_id, 1 AS depth, ARRAY[id] AS path
FROM categories WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, c.parent_id, t.depth + 1, t.path || c.id
FROM categories c JOIN tree t ON c.parent_id = t.id
)
SELECT repeat(' ', depth - 1) || name AS category FROM tree ORDER BY path; category
--------------
Furniture
Chairs
Desks
Standing
Lighting
(5 rows)SEARCH and CYCLE clauses
SEARCH DEPTH FIRST or BREADTH FIRST adds an ordering column without building path arrays by hand, and CYCLE stops the recursion when a row repeats, which protects you from infinite loops in data that is supposed to be a tree but is not.
WITH RECURSIVE tree AS (
SELECT id, parent_id, name FROM categories WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.parent_id, c.name FROM categories c JOIN tree t ON c.parent_id = t.id
) SEARCH DEPTH FIRST BY id SET ordercol
CYCLE id SET is_cycle USING path
SELECT name FROM tree ORDER BY ordercol;Data-modifying CTE: move rows in one statement
Every part of the statement sees the same snapshot and commits together, so rows cannot be deleted without being archived or archived twice. The RETURNING rows of the DELETE feed the INSERT directly, with no temporary table.
WITH moved AS (
DELETE FROM orders
WHERE created_at < now() - interval '2 years'
RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;INSERT 0 18244Latest row per group, three ways
DISTINCT ON is the shortest, row_number() is portable to other databases, and LATERAL with LIMIT 1 is the fastest when there are few customers and many orders per customer, because it does one short index scan per customer instead of sorting all orders.
SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC;
SELECT * FROM (
SELECT o.*, row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn FROM orders o
) t WHERE rn = 1;
SELECT c.id, last.* FROM customers c
CROSS JOIN LATERAL (SELECT * FROM orders o WHERE o.customer_id = c.id ORDER BY created_at DESC LIMIT 1) last;Window Functions
Ranking
row_number, rank, dense_rank
A window function computes over a set of rows related to the current row without collapsing them the way GROUP BY does. row_number breaks ties arbitrarily, rank leaves gaps after ties and dense_rank does not. A named WINDOW clause avoids repeating the same OVER definition.
SELECT name, category, price,
row_number() OVER w AS rn,
rank() OVER w AS rnk,
dense_rank() OVER w AS dense
FROM products
WINDOW w AS (PARTITION BY category ORDER BY price DESC); name | category | price | rn | rnk | dense
-------------+----------+--------+----+-----+-------
Oak desk | desks | 410.00 | 1 | 1 | 1
Walnut desk | desks | 410.00 | 2 | 1 | 1
Pine desk | desks | 199.00 | 3 | 3 | 2
(3 rows)Top N per group
SELECT * FROM (
SELECT p.*, row_number() OVER (PARTITION BY category ORDER BY sold DESC) AS rn
FROM products p
) ranked
WHERE rn <= 3;Running and Moving Values
Running total, share of total, change from previous
SELECT created_at::date AS day, total,
sum(total) OVER (ORDER BY created_at) AS running,
round(100 * total / sum(total) OVER (), 1) AS pct,
total - lag(total) OVER (ORDER BY created_at) AS diff
FROM orders WHERE customer_id = 12; day | total | running | pct | diff
------------+--------+---------+------+---------
2026-07-02 | 249.50 | 249.50 | 36.4 |
2026-08-14 | 25.25 | 274.75 | 3.7 | -224.25
2026-09-28 | 410.00 | 684.75 | 59.9 | 384.75
(3 rows)Moving averages with frames
ROWS counts physical rows, so a missing day makes the window reach further back in time; RANGE with an interval uses the values of the ORDER BY column, so the window always covers seven calendar days. The default frame with ORDER BY is RANGE UNBOUNDED PRECEDING, which is why last_value() usually returns the current row unless you widen the frame.
SELECT day, revenue,
avg(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_7_rows,
avg(revenue) OVER (ORDER BY day RANGE BETWEEN interval '6 days' PRECEDING AND CURRENT ROW) AS avg_7_days
FROM daily_revenue;first, last and nth values
SELECT customer_id, created_at,
first_value(total) OVER w AS first_order,
last_value(total) OVER w AS last_order,
nth_value(total, 2) OVER w AS second_order
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);IGNORE NULLS in window functions, PostgreSQL 19
Filling gaps with the last known value used to need a subquery that grouped runs of NULLs. PostgreSQL 19 accepts IGNORE NULLS on lag, lead, first_value, last_value and nth_value, as the SQL standard specifies. 19 is at the release candidate stage as of late September 2026, so confirm against the final release notes.
SELECT day, price,
lag(price) IGNORE NULLS OVER (ORDER BY day) AS last_known_price
FROM price_history;Patterns
Gaps and islands: consecutive active days
Subtracting a row number from a date gives the same value for every day in an unbroken run, because both increase by one per row; a gap changes the difference. Grouping by that difference turns each run into one row.
SELECT user_id, min(day) AS streak_start, max(day) AS streak_end, count(*) AS days
FROM (
SELECT user_id, day, day - (row_number() OVER (PARTITION BY user_id ORDER BY day))::int AS grp
FROM (SELECT DISTINCT user_id, created_at::date AS day FROM events) d
) t
GROUP BY user_id, grp
ORDER BY days DESC LIMIT 5; user_id | streak_start | streak_end | days
---------+--------------+------------+------
12 | 2026-09-01 | 2026-09-21 | 21
40 | 2026-08-11 | 2026-08-19 | 9
(2 rows)Sessions: a new session after 30 idle minutes
SELECT user_id, ts, sum(new_session) OVER (PARTITION BY user_id ORDER BY ts) AS session_no
FROM (
SELECT user_id, ts,
CASE WHEN ts - lag(ts) OVER (PARTITION BY user_id ORDER BY ts) <= interval '30 minutes' THEN 0 ELSE 1 END AS new_session
FROM events
) e;Distribution: percent_rank, cume_dist, ntile
SELECT id, total,
round(percent_rank() OVER (ORDER BY total)::numeric, 3) AS pct_rank,
ntile(4) OVER (ORDER BY total) AS quartile
FROM orders WHERE customer_id = 12; id | total | pct_rank | quartile
-------+--------+----------+----------
10051 | 25.25 | 0.000 | 1
10042 | 249.50 | 0.500 | 2
10060 | 410.00 | 1.000 | 3
(3 rows)Built-in Functions
Strings
The string functions you use every week
SELECT concat_ws(' ', first_name, last_name) AS full_name, -- skips NULLs
first_name || ' ' || last_name AS joined, -- NULL if either is NULL
upper(email), initcap('ana maria'), length('ăîș'),
left(sku, 3), right(sku, 2), lpad(id::text, 6, '0'),
trim(' x '), replace(phone, ' ', ''), position('@' IN email)
FROM customers LIMIT 1;format(): safe string building
%I quotes an identifier only when needed and %L quotes a literal safely, including NULL, so format() is the correct way to build dynamic SQL in PL/pgSQL. Concatenating values into SQL text is how injection happens.
SELECT format('Hello %s, you have %s orders', name, order_count) FROM customer_stats;
SELECT format('SELECT count(*) FROM %I.%I WHERE status = %L', 'public', 'Orders', 'paid'); format
------------------------------------------------------------
SELECT count(*) FROM public."Orders" WHERE status = 'paid'
(1 row)Split, join and pick apart
SELECT split_part('2026-09-29', '-', 2); -- 09
SELECT string_to_array('oak,ash,elm', ','); -- {oak,ash,elm}
SELECT array_to_string(ARRAY['a', 'b'], ' | ');
SELECT regexp_split_to_table('a1b22c', '\d+'); -- a, b, c
SELECT * FROM unnest(string_to_array('x;y;z', ';')) WITH ORDINALITY AS t(item, n);Regular expressions
SELECT regexp_replace('Oak desk', '\s+', ' ', 'g');
SELECT (regexp_match('SKU OAK-1204', '([A-Z]+)-(\d+)'))[2]; -- first match, as an array
SELECT regexp_matches('a1 b2 c3', '([a-z])(\d)', 'g'); -- every match, one row each
SELECT 'OAK-1' ~ '^[A-Z]+-\d+$' AS valid; regexp_match
--------------
1204
(1 row)regexp_count, regexp_substr, regexp_instr, regexp_like
SELECT regexp_count('banana', 'a'), regexp_substr('Order #10042', '\d+');
SELECT regexp_instr('Order #10042', '\d'), regexp_like('OAK-1', '^[A-Z]+-\d+$'); regexp_count | regexp_substr
--------------+---------------
3 | 10042
(1 row)casefold() for case insensitive comparison
lower() maps characters one to one, which is not enough for languages where case folding changes the length of a string. casefold(), new in 18, applies full Unicode case folding with a collation that supports it, so it is the right function for case insensitive comparisons and indexes. On older versions, lower() or the citext extension are the usual choices.
SELECT casefold('Straße') = casefold('STRASSE');
CREATE INDEX ON customers (casefold(email));
SELECT * FROM customers WHERE casefold(email) = casefold('Ana@Example.com');Dates
Truncate, extract, format, parse
SELECT date_trunc('day', now()), date_trunc('month', now()), date_trunc('year', now());
SELECT extract(year FROM now()), extract(isodow FROM now()), extract(epoch FROM now());
SELECT to_char(now(), 'YYYY-MM-DD HH24:MI'), to_char(1234567.8, 'FM9G999G990D00');
SELECT to_date('29.09.2026', 'DD.MM.YYYY'), to_timestamp(1790000000); to_char | to_char
------------------+--------------
2026-09-29 10:14 | 1,234,567.80
(1 row)now() versus clock_timestamp()
now(), current_timestamp and transaction_timestamp() return the start time of the current transaction, so every row inserted in one transaction gets the same timestamp. clock_timestamp() returns the actual time at each call, which is what you want for measuring durations inside a function.
BEGIN;
SELECT now(), clock_timestamp();
SELECT pg_sleep(2);
SELECT now(), clock_timestamp(); -- now() is unchanged inside the transaction
COMMIT;Bucket timestamps with date_bin
SELECT date_bin('15 minutes', created_at, '2026-01-01') AS bucket, count(*)
FROM events GROUP BY 1 ORDER BY 1; bucket | count
------------------------+-------
2026-09-29 10:00:00+00 | 412
2026-09-29 10:15:00+00 | 389
(2 rows)Numbers and Conditionals
Rounding, ranges, buckets, random
SELECT round(2.567, 2), trunc(2.567, 1), ceil(2.1), floor(-2.1), abs(-5);
SELECT greatest(3, 7, 5), least(3, 7, 5);
SELECT width_bucket(total, 0, 500, 5) AS bucket, count(*) FROM orders GROUP BY 1 ORDER BY 1;
SELECT random(), floor(random() * 6 + 1)::int AS die;random(min, max)
From 17, random() accepts an integer or numeric range and returns a value in it, inclusive at both ends, so the floor(random() * n + 1) idiom is no longer needed.
SELECT random(1, 6) AS die, random(0.0, 1.0) AS fraction;
SELECT setseed(0.42); SELECT random(1, 100); -- repeatable within the sessionConditional helpers
SELECT coalesce(nickname, name) FROM customers;
SELECT nullif(trim(phone), '') FROM customers; -- empty string becomes NULL
SELECT greatest(updated_at, created_at) FROM orders; -- ignores NULLs
SELECT num_nulls(phone, email, address), num_nonnulls(phone, email, address) FROM customers;Insert, Update, MERGE
Insert and Upsert
INSERT with RETURNING
RETURNING hands back the generated id, defaults and computed columns in the same round trip, so there is no need for a follow up SELECT or lastval(). It works on UPDATE, DELETE and MERGE too.
INSERT INTO customers (name, email) VALUES ('Ana', 'ana@example.com') RETURNING id, created_at;
INSERT INTO customers (name, email) VALUES ('Radu', 'radu@example.com'), ('Ioana', 'ioana@example.com');
INSERT INTO orders_archive SELECT * FROM orders WHERE created_at < '2025-01-01';
INSERT INTO settings DEFAULT VALUES; id | created_at
-----+-------------------------------
813 | 2026-09-29 10:14:02.118427+00
(1 row)
INSERT 0 1Upsert with ON CONFLICT
ON CONFLICT needs a unique index or constraint to arbitrate on, named by its columns or ON CONSTRAINT name. EXCLUDED is the row you tried to insert. The WHERE clause skips updates that would change nothing, which saves writes and dead rows; xmax = 0 is a well known trick to tell an insert from an update in RETURNING.
INSERT INTO products (sku, name, price) VALUES ('OAK-1', 'Oak desk', 199)
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name, price = EXCLUDED.price, updated_at = now()
WHERE products.price IS DISTINCT FROM EXCLUDED.price
RETURNING id, (xmax = 0) AS inserted;
INSERT INTO tags (name) VALUES ('oak') ON CONFLICT DO NOTHING; id | inserted
----+----------
41 | f
(1 row)
INSERT 0 1ON CONFLICT DO SELECT, PostgreSQL 19
The get or create pattern needs the id whether the row was inserted or already there; before 19 that takes DO UPDATE SET name = EXCLUDED.name, which writes a new row version, or a second query. DO SELECT returns the conflicting row instead, optionally locked. It is in the PostgreSQL 19 documentation and release notes; 19 was at the release candidate stage in late September 2026.
INSERT INTO tags (name) VALUES ('oak')
ON CONFLICT (name) DO SELECT
RETURNING id; -- the new row's id, or the existing row's
INSERT INTO tags (name) VALUES ('oak')
ON CONFLICT (name) DO SELECT FOR UPDATE
RETURNING *; -- and lock the existing rowUpdate and Delete
UPDATE and DELETE, with RETURNING
UPDATE products SET price = price * 1.10 WHERE category = 'desks' RETURNING id, price;
DELETE FROM sessions WHERE expires_at < now() RETURNING id;
UPDATE orders SET status = 'shipped', shipped_at = now() WHERE id = 10042;UPDATE 1UPDATE FROM and DELETE USING: change rows based on another table
If the FROM side matches a target row more than once, PostgreSQL updates it with one of the matches, chosen unpredictably, and reports no error. Aggregate the source first, as above, so every target row matches at most once.
UPDATE customers c
SET lifetime_value = x.total, last_order_at = x.last_at
FROM (SELECT customer_id, sum(total) AS total, max(created_at) AS last_at FROM orders GROUP BY 1) x
WHERE x.customer_id = c.id;
DELETE FROM order_items i
USING orders o
WHERE o.id = i.order_id AND o.status = 'cancelled';UPDATE 188120RETURNING OLD and NEW values
From 18, RETURNING can read the row as it was before the change (old) and after it (new) in INSERT, UPDATE, DELETE and MERGE, which makes audit logging and change detection a single statement.
UPDATE products SET price = price * 1.10 WHERE id = 41
RETURNING old.price AS before, new.price AS after;
DELETE FROM carts WHERE id = 7 RETURNING old.*; before | after
--------+--------
199.00 | 218.90
(1 row)Delete millions of rows without one giant transaction
One DELETE of fifty million rows holds its locks for the whole run, bloats the table in one go and generates a burst of WAL that replicas must replay. Batches of a few thousand rows, committed one by one, keep locks short and let autovacuum keep up. With time partitioned tables, DROP or DETACH of an old partition beats any DELETE.
DELETE FROM events
WHERE ctid IN (SELECT ctid FROM events WHERE created_at < now() - interval '90 days' LIMIT 10000);
-- repeat until it reports DELETE 0; or drop a whole partition, which is instantDELETE 10000TRUNCATE: empty tables instantly
TRUNCATE sessions;
TRUNCATE orders, order_items RESTART IDENTITY; -- also reset identity sequences
TRUNCATE customers CASCADE; -- and every table that references itUpsert Two Ways
INSERT ... ON CONFLICT: safe under concurrency
ON CONFLICT relies on a unique index to arbitrate, so two sessions upserting the same key at the same moment never both insert: one inserts and the other updates. Use it for single rows and batches coming from an application.
INSERT INTO stock (sku, qty) VALUES ('OAK-1', 12)
ON CONFLICT (sku) DO UPDATE SET qty = EXCLUDED.qty, updated_at = now();MERGE: many actions, one statement, no unique index needed
MERGE can insert, update and delete in one pass and works without a unique constraint, which suits syncing from a staging table in a batch job. It does not arbitrate concurrent inserts the way ON CONFLICT does, so two sessions merging the same new key can both try to insert and one fails with a unique violation.
MERGE INTO stock t
USING (VALUES ('OAK-1', 12)) AS s(sku, qty) ON s.sku = t.sku
WHEN MATCHED AND s.qty = 0 THEN DELETE
WHEN MATCHED THEN UPDATE SET qty = s.qty
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (s.sku, s.qty);MERGE
MERGE: sync a staging table into a target
MERGE applies the first matching WHEN clause to each source row, so one statement can insert, update and delete. Unlike ON CONFLICT it does not need a unique index, but it is not protected against a concurrent insert of the same key: two sessions merging the same new sku at once can both take the NOT MATCHED branch and one fails with a unique violation.
MERGE INTO products p
USING staging_products s ON s.sku = p.sku
WHEN MATCHED AND s.discontinued THEN DELETE
WHEN MATCHED THEN UPDATE SET name = s.name, price = s.price
WHEN NOT MATCHED THEN INSERT (sku, name, price) VALUES (s.sku, s.name, s.price);MERGE 1284MERGE with RETURNING and NOT MATCHED BY SOURCE
MERGE INTO stock t
USING feed f ON f.sku = t.sku
WHEN MATCHED THEN UPDATE SET qty = f.qty
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (f.sku, f.qty)
WHEN NOT MATCHED BY SOURCE THEN DELETE
RETURNING merge_action(), t.sku, t.qty; merge_action | sku | qty
--------------+-------+-----
UPDATE | OAK-1 | 12
INSERT | ELM-2 | 7
DELETE | ASH-4 | 5
(3 rows)Bulk Load with COPY
COPY from and to server files
COPY is the fastest way to load data, often ten times faster than batched INSERTs. The file path is on the database server, so it needs superuser or the pg_read_server_files and pg_write_server_files roles; from a laptop or on a managed service, use psql's \copy or COPY ... FROM STDIN from the driver.
COPY products (sku, name, price) FROM '/var/lib/postgresql/import/products.csv' WITH (FORMAT csv, HEADER true);
COPY (SELECT * FROM orders WHERE created_at >= '2026-09-01') TO '/tmp/september.csv' WITH (FORMAT csv, HEADER true);Skip bad rows instead of failing the whole load
COPY products FROM STDIN WITH (FORMAT csv, HEADER true, ON_ERROR ignore, LOG_VERBOSITY verbose);NOTICE: skipping row due to data type incompatibility at line 1842 for column "price": "12,50"
NOTICE: 1 row was skipped due to data type incompatibility
COPY 48212Stop after too many bad rows
ON_ERROR ignore alone would happily skip every row of a file in the wrong format. REJECT_LIMIT, added in 18, makes COPY fail once more than that many rows were rejected, so a broken file stops the load instead of producing an empty table.
COPY products FROM STDIN WITH (FORMAT csv, HEADER true, ON_ERROR ignore, REJECT_LIMIT 100);Watch a long COPY
SELECT relid::regclass, command, type, bytes_processed, bytes_total, tuples_processed, tuples_excluded
FROM pg_stat_progress_copy; -- 14+ relid | command | type | bytes_processed | bytes_total | tuples_processed | tuples_excluded
----------+-----------+------+-----------------+-------------+------------------+-----------------
products | COPY FROM | FILE | 412091338 | 980110244 | 2044180 | 0
(1 row)JSON & JSONB
Read JSON
The operators: -> ->> #> #>>
-> returns jsonb so you can keep navigating, ->> returns text for comparisons and casts. A missing key gives NULL rather than an error. Use jsonb rather than json for almost everything: it is stored parsed, compares and indexes properly, and drops duplicate keys; json only keeps the original text and key order.
SELECT meta -> 'address' AS address_json, -- jsonb
meta ->> 'tier' AS tier, -- text
meta #> '{address,city}' AS city_json, -- by path, jsonb
meta #>> '{address,city}' AS city, -- by path, text
meta -> 'tags' -> 0 AS first_tag,
(meta ->> 'score')::int + 1 AS score_plus_one
FROM customers WHERE id = 12; tier | city | first_tag | score_plus_one
------+------+-----------+----------------
gold | Cluj | "vip" | 88
(1 row)Containment and existence
SELECT * FROM customers WHERE meta @> '{"tier": "gold"}'; -- contains
SELECT * FROM customers WHERE meta ? 'phone'; -- top level key exists
SELECT * FROM customers WHERE meta ?| ARRAY['phone', 'mobile']; -- any of these keys
SELECT * FROM customers WHERE meta -> 'tags' @> '["vip"]'; -- array contains an element
SELECT * FROM events WHERE payload @? '$.items[*] ? (@.qty > 10)'; -- jsonpath matchjsonpath queries
SELECT jsonb_path_query(payload, '$.items[*].sku') FROM events WHERE id = 7;
SELECT jsonb_path_query_array(payload, '$.items[*] ? (@.price > 100).sku') FROM events WHERE id = 7;
SELECT jsonb_path_exists(payload, '$.customer.email ? (@ like_regex "@example\\.com$")') FROM events; jsonb_path_query
------------------
"OAK-1"
"ASH-4"
(2 rows)Change JSON
Set, add and remove keys
Every jsonb update writes a whole new copy of the value and a new row version, even when one key changes, so large documents that change often are expensive. Keep frequently updated fields in normal columns and the flexible, rarely changed part in jsonb.
UPDATE customers SET meta = jsonb_set(meta, '{address,city}', '"Iasi"') WHERE id = 12;
UPDATE customers SET meta = meta || '{"tier": "platinum", "vip": true}' WHERE id = 12; -- merge, right side wins
UPDATE customers SET meta = meta - 'legacy_id' WHERE id = 12; -- remove a key
UPDATE customers SET meta = meta #- '{address,zip}' WHERE id = 12; -- remove by path
UPDATE customers SET meta['tier'] = '"gold"' WHERE id = 12; -- subscripting, 14+Build JSON from rows
SELECT jsonb_build_object('id', id, 'name', name, 'orders', (
SELECT coalesce(jsonb_agg(jsonb_build_object('id', o.id, 'total', o.total) ORDER BY o.id), '[]')
FROM orders o WHERE o.customer_id = c.id)) AS doc
FROM customers c WHERE id = 12;
SELECT to_jsonb(c) - 'password_hash' FROM customers c WHERE id = 12; -- a whole row, minus a column doc
-------------------------------------------------------------------------------------------------------
{"id": 12, "name": "Ana", "orders": [{"id": 10042, "total": 249.50}, {"id": 10060, "total": 410.00}]}
(1 row)Turn JSON into rows
SELECT key, value FROM jsonb_each('{"a": 1, "b": [2, 3]}');
SELECT elem ->> 'sku' AS sku, (elem ->> 'qty')::int AS qty FROM events, jsonb_array_elements(payload -> 'items') AS elem;
SELECT * FROM jsonb_to_recordset('[{"sku": "OAK-1", "qty": 2}, {"sku": "ASH-4", "qty": 1}]') AS t(sku text, qty int); sku | qty
-------+-----
OAK-1 | 2
ASH-4 | 1
(2 rows)SQL/JSON and Indexes
JSON_TABLE, JSON_VALUE, JSON_QUERY, JSON_EXISTS
PostgreSQL 17 adds the SQL standard JSON query functions. JSON_TABLE turns a JSON document into a relational table with typed columns in the FROM clause, which replaces chains of jsonb_array_elements and casts; the same queries also run on Oracle and other databases that follow the standard.
SELECT jt.* FROM events e,
JSON_TABLE(e.payload, '$.items[*]' COLUMNS (
sku text PATH '$.sku',
qty int PATH '$.qty' DEFAULT 1 ON EMPTY,
price numeric(10,2) PATH '$.price'
)) AS jt
WHERE e.id = 7;
SELECT JSON_VALUE(payload, '$.customer.email'), JSON_QUERY(payload, '$.items[0]'), JSON_EXISTS(payload, '$.coupon') FROM events; sku | qty | price
-------+-----+--------
OAK-1 | 2 | 199.00
ASH-4 | 1 | 89.00
(2 rows)Index JSONB
A GIN index helps containment (@>) and jsonpath operators, not ->> comparisons. A query written as meta ->> 'tier' = 'gold' needs an expression B-tree index on exactly that expression, while meta @> '{"tier": "gold"}' can use the GIN index. Choose the query shape and the index together.
CREATE INDEX ON customers USING gin (meta jsonb_path_ops); -- @>, @? and @@, smaller and faster
CREATE INDEX ON customers USING gin (meta); -- also ? ?| ?& key existence
CREATE INDEX ON customers ((meta ->> 'tier')); -- one key, B-tree, for = and ranges
EXPLAIN SELECT * FROM customers WHERE meta @> '{"tier": "gold"}'; QUERY PLAN
------------------------------------------------------------------------------------
Bitmap Heap Scan on customers (cost=28.14..512.40 rows=210 width=96)
Recheck Cond: (meta @> '{"tier": "gold"}'::jsonb)
-> Bitmap Index Scan on customers_meta_idx (cost=0.00..28.09 rows=210 width=0)
Index Cond: (meta @> '{"tier": "gold"}'::jsonb)Validate and construct with SQL/JSON
SELECT '{"a": 1}' IS JSON OBJECT, '[1, 2]' IS JSON ARRAY, 'oops' IS JSON;
SELECT JSON_OBJECT('id': 12, 'tier': 'gold'), JSON_ARRAY(1, 'two', NULL ABSENT ON NULL);
ALTER TABLE raw_events ADD CONSTRAINT payload_is_json CHECK (body IS JSON OBJECT);Arrays & Ranges
Arrays
Array columns and literals
CREATE TABLE products (id bigint PRIMARY KEY, name text, tags text[] NOT NULL DEFAULT '{}');
INSERT INTO products VALUES (1, 'Oak desk', ARRAY['wood', 'desk']), (2, 'Ash shelf', '{wood,shelf}');
SELECT tags[1], tags[2:3], cardinality(tags), array_length(tags, 1) FROM products; -- 1 based
UPDATE products SET tags = array_append(tags, 'sale') WHERE id = 1;
UPDATE products SET tags = array_remove(tags, 'sale');
SELECT array_position(tags, 'desk') FROM products WHERE id = 1; tags | tags | cardinality | array_length
------+--------+-------------+--------------
wood | {desk} | 2 | 2
(1 row)Search inside arrays
'x' = ANY (tags) cannot use a GIN index, while tags @> ARRAY['x'] can, so write containment when the table is large. Arrays are handy for tags and small lists; if you need to join on the elements or enforce foreign keys, a separate table is still the better model.
SELECT * FROM products WHERE 'desk' = ANY (tags); -- element match
SELECT * FROM products WHERE tags @> ARRAY['wood', 'desk']; -- has all of these
SELECT * FROM products WHERE tags && ARRAY['sale', 'new']; -- has any of these
CREATE INDEX ON products USING gin (tags); -- makes @> and && fastunnest and array_agg: rows to arrays and back
SELECT p.name, t.tag, t.pos FROM products p, unnest(p.tags) WITH ORDINALITY AS t(tag, pos);
SELECT customer_id, array_agg(id ORDER BY created_at) FROM orders GROUP BY 1;
SELECT * FROM unnest(ARRAY[1, 2, 3], ARRAY['a', 'b', 'c']) AS t(n, letter); -- zip name | tag | pos
----------+------+-----
Oak desk | wood | 1
Oak desk | desk | 2
(2 rows)array_sort and array_reverse
PostgreSQL 18 adds array_sort() and array_reverse(); before that the usual idiom is ARRAY(SELECT unnest(a) ORDER BY 1).
SELECT array_sort(ARRAY[3, 1, 2]), array_reverse(ARRAY[1, 2, 3]);
SELECT array_sort(tags, descending => true) FROM products;Build, clean and compare arrays
SELECT ARRAY(SELECT DISTINCT unnest(tags) ORDER BY 1) FROM products; -- dedupe and sort
SELECT array_agg(sku) FILTER (WHERE qty = 0) AS out_of_stock FROM stock;
SELECT ARRAY[1, 2] = ARRAY[2, 1] AS same_order, ARRAY[1, 2] <@ ARRAY[2, 1, 3] AS subset; same_order | subset
------------+--------
f | t
(1 row)Ranges
Range types and operators
A range stores both ends and whether each is inclusive; the half open form [start, end) is the convention because consecutive ranges then meet without overlapping. Operators such as && (overlaps) and @> (contains) use GiST indexes, and exclusion constraints on ranges prevent double bookings.
SELECT '[2026-10-01,2026-10-05)'::daterange @> '2026-10-03'::date AS contains,
'[1,10)'::int4range && '[5,20)'::int4range AS overlaps,
lower('[2026-10-01,2026-10-05)'::daterange), upper('[2026-10-01,2026-10-05)'::daterange),
isempty('[5,5)'::int4range);
SELECT * FROM bookings WHERE during && tstzrange('2026-10-01', '2026-10-02');
CREATE INDEX ON bookings USING gist (during); contains | overlaps | lower | upper
----------+----------+------------+------------
t | t | 2026-10-01 | 2026-10-05
(1 row)Multiranges and range_agg
SELECT range_agg(during) FROM bookings WHERE room_id = 1; -- merged busy periods
SELECT datemultirange('[2026-10-01,2026-10-10)') - datemultirange('[2026-10-03,2026-10-05)'); ?column?
---------------------------------------------------
{[2026-10-01,2026-10-03),[2026-10-05,2026-10-10)}
(1 row)Transactions & Locks
Transactions
BEGIN, COMMIT, ROLLBACK, SAVEPOINT
In PostgreSQL, after any error inside a transaction block, every following statement fails with current transaction is aborted until you ROLLBACK or roll back to a savepoint. DDL is transactional too, so CREATE TABLE and ALTER TABLE can be rolled back, which makes migrations far safer than in MySQL.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
BEGIN;
INSERT INTO orders (customer_id, total) VALUES (12, 50);
SAVEPOINT before_items;
INSERT INTO order_items (order_id, sku) VALUES (currval('orders_id_seq'), 'NOPE'); -- fails
ROLLBACK TO SAVEPOINT before_items;
COMMIT;Isolation levels
READ COMMITTED, the default, takes a new snapshot for every statement. REPEATABLE READ keeps one snapshot for the whole transaction. SERIALIZABLE additionally detects patterns that could not happen if the transactions had run one after another and aborts one of them with SQLSTATE 40001, so code using it must retry the whole transaction.
SHOW default_transaction_isolation; -- read committed
BEGIN ISOLATION LEVEL REPEATABLE READ; -- one snapshot for the whole transaction
BEGIN ISOLATION LEVEL SERIALIZABLE; -- as if transactions ran one at a time
BEGIN READ ONLY;
SET default_transaction_isolation = 'serializable'; -- per sessionERROR: could not serialize access due to read/write dependencies among transactions
DETAIL: Reason code: Canceled on identification as a pivot, during commit attempt.
HINT: The transaction might succeed if retried.Row Locks and Queues
Read, lock, decide, write
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; -- others wait to lock or update this row
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;
SELECT * FROM accounts WHERE id = 1 FOR NO KEY UPDATE; -- weaker: does not block inserts of child rows
SELECT * FROM seats WHERE id = 42 FOR UPDATE NOWAIT; -- fail at once instead of waitingERROR: could not obtain lock on row in relation "seats"A job queue with SKIP LOCKED
SKIP LOCKED makes each worker take rows nobody else has locked, so many workers can pull from one table without blocking each other or processing a job twice. A partial index on (run_at) WHERE status = 'queued' keeps the lookup fast as finished jobs pile up.
WITH next AS (
SELECT id FROM jobs
WHERE status = 'queued' AND run_at <= now()
ORDER BY run_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE jobs j SET status = 'running', started_at = now(), worker = 'w3'
FROM next WHERE j.id = next.id
RETURNING j.id, j.payload;Advisory locks: application level mutexes
Advisory locks lock a number, not a row, so they are a cheap way to make sure only one instance of a cron job or migration runs at a time across many servers. Session level locks survive COMMIT and must be released explicitly; with a transaction pooler such as PgBouncer, prefer the transaction level variant.
SELECT pg_try_advisory_lock(hashtext('nightly-report')); -- true if you got it, session lifetime
SELECT pg_advisory_unlock(hashtext('nightly-report'));
SELECT pg_advisory_xact_lock(42); -- released at COMMIT or ROLLBACK pg_try_advisory_lock
----------------------
t
(1 row)Waiting, Blocking and Timeouts
Who is blocking whom
SELECT a.pid, a.usename, a.state, now() - a.xact_start AS in_tx,
pg_blocking_pids(a.pid) AS blocked_by, left(a.query, 60) AS query
FROM pg_stat_activity a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0; pid | usename | state | in_tx | blocked_by | query
-------+---------+--------+----------+------------+-----------------------------------
48301 | app | active | 00:00:41 | {48213} | UPDATE orders SET status = 'paid'
(1 row)Timeouts that save you
A session left idle inside a transaction holds its locks and stops VACUUM from removing dead rows everywhere, which slowly degrades the whole database. idle_in_transaction_session_timeout ends such sessions; statement_timeout and lock_timeout keep a single bad query or migration from piling up everything behind it.
SET lock_timeout = '5s'; -- give up waiting for a lock
SET statement_timeout = '30s'; -- cancel long queries
SET idle_in_transaction_session_timeout = '60s'; -- kill sessions that BEGIN and wander off
ALTER ROLE app SET statement_timeout = '15s'; -- default for every session of a roletransaction_timeout
statement_timeout limits one statement and idle_in_transaction_session_timeout limits idle gaps, but neither stops a transaction made of many quick statements from running for hours. transaction_timeout, added in 17, caps the whole transaction.
SET transaction_timeout = '5min';
ALTER ROLE batch_jobs SET transaction_timeout = '30min';Which lock each statement takes, and what it blocks
| Statements | Lock | Blocks |
|---|---|---|
SELECT | ACCESS SHARE | only ACCESS EXCLUSIVE |
SELECT ... FOR UPDATE / FOR SHARE | ROW SHARE | EXCLUSIVE, ACCESS EXCLUSIVE |
INSERT, UPDATE, DELETE, MERGE | ROW EXCLUSIVE | SHARE and stronger, so a plain CREATE INDEX |
VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY, VALIDATE CONSTRAINT | SHARE UPDATE EXCLUSIVE | other maintenance and schema changes, not reads or writes |
CREATE INDEX | SHARE | every write |
CREATE TRIGGER, ADD FOREIGN KEY | SHARE ROW EXCLUSIVE | writes and other DDL |
REFRESH MATERIALIZED VIEW CONCURRENTLY | EXCLUSIVE | writes and row locks, not plain reads |
DROP, TRUNCATE, most ALTER TABLE, VACUUM FULL, REFRESH MATERIALIZED VIEW | ACCESS EXCLUSIVE | everything, even SELECT |
Deadlocks
PostgreSQL detects the cycle and cancels one transaction, which the application should retry. The lasting fix is to lock rows in a consistent order, for example by always updating accounts in ascending id order, and to keep transactions short.
-- session 1: UPDATE accounts SET ... WHERE id = 1; then WHERE id = 2
-- session 2: UPDATE accounts SET ... WHERE id = 2; then WHERE id = 1
SHOW deadlock_timeout; -- 1s: how long to wait before checking for a deadlock
SET log_lock_waits = on; -- log waits longer than deadlock_timeoutERROR: deadlock detected
DETAIL: Process 48301 waits for ShareLock on transaction 912044; blocked by process 48213.
Process 48213 waits for ShareLock on transaction 912045; blocked by process 48301.
HINT: See server log for query details.Full Text Search
Full Text Search
Match documents against a query
to_tsvector splits text into normalized lexemes: stop words such as the disappear and words are reduced to their stems, so foxes matches fox. websearch_to_tsquery accepts what users type into a search box, with quotes, minus and or, and never raises a syntax error.
SELECT to_tsvector('english', 'The quick brown foxes jumped');
SELECT to_tsvector('english', 'foxes jumping') @@ to_tsquery('english', 'fox & jump');
SELECT websearch_to_tsquery('english', '"oak desk" -pine or walnut'); -- search box syntax to_tsvector
--------------------------------------
'brown':3 'fox':4 'jump':5 'quick':2
(1 row)A searchable column with a GIN index
ALTER TABLE articles ADD COLUMN search tsvector
GENERATED ALWAYS AS (setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')) STORED;
CREATE INDEX ON articles USING gin (search);
SELECT id, title, ts_rank(search, q) AS rank
FROM articles, websearch_to_tsquery('english', 'postgres vacuum') q
WHERE search @@ q
ORDER BY rank DESC LIMIT 10; id | title | rank
-----+-------------------------------+--------
118 | Tuning autovacuum on Postgres | 0.9148
204 | VACUUM FULL versus pg_repack | 0.6079
(2 rows)Highlight the matches
ts_headline re-parses the original text, so it is slow; run it only on the few rows you display, after ranking and LIMIT, never across the whole table. Escape the result before inserting it into HTML, since the document text itself may contain markup.
SELECT ts_headline('english', body, websearch_to_tsquery('english', 'vacuum'),
'StartSel=<mark>, StopSel=</mark>, MaxWords=30, MinWords=10')
FROM articles WHERE id = 118;Prefix and phrase search
:* matches every lexeme starting with the prefix, which powers autocomplete boxes. <-> means followed by, and <N> means N positions later, so phrase search respects word order that plain & ignores.
SELECT title FROM articles WHERE search @@ to_tsquery('english', 'postg:*'); -- prefix: search as you type
SELECT title FROM articles WHERE search @@ phraseto_tsquery('english', 'point in time recovery');
SELECT to_tsquery('english', 'logical <-> replication'), to_tsquery('english', 'vacuum <2> table'); to_tsquery | to_tsquery
----------------------+---------------------
'logic' <-> 'replic' | 'vacuum' <2> 'tabl'
(1 row)Fuzzy Matching
Trigrams: typo tolerant search and fast ILIKE
pg_trgm breaks strings into three character pieces and compares how many they share, which tolerates typos in names and product titles where full text search, built for words, does not. Its GIN index also accelerates LIKE and ILIKE with leading wildcards and regular expression searches.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX ON customers USING gin (name gin_trgm_ops);
SELECT name, similarity(name, 'Jonh Smiht') AS score
FROM customers WHERE name % 'Jonh Smiht' ORDER BY score DESC LIMIT 5;
SELECT * FROM customers WHERE name ILIKE '%smith%'; -- the same index serves this name | score
------------+------------
John Smith | 0.375
Jon Smythe | 0.29411766
(2 rows)Ignore accents
CREATE EXTENSION IF NOT EXISTS unaccent;
SELECT unaccent('Brașov, Timișoara, São Paulo');
CREATE TEXT SEARCH CONFIGURATION ro_unaccent (COPY = simple);
ALTER TEXT SEARCH CONFIGURATION ro_unaccent ALTER MAPPING FOR hword, hword_part, word WITH unaccent, simple; unaccent
------------------------------
Brasov, Timisoara, Sao Paulo
(1 row)Indexes
Create the Right Index
B-tree basics and multicolumn order
A multicolumn B-tree is sorted by the first column, then the second within it, so equality columns go first and the range or ORDER BY column last. Before 18, a condition on only the second column usually could not use the index; the skip scan added in 18 helps when the leading column has few distinct values, but the right column order is still the reliable fix.
CREATE INDEX CONCURRENTLY orders_customer_created_idx ON orders (customer_id, created_at DESC);
-- serves: WHERE customer_id = ? (leftmost column)
-- serves: WHERE customer_id = ? ORDER BY created_at DESC LIMIT 10
-- serves: WHERE customer_id = ? AND created_at >= ?
-- 18+ can also skip scan it for: WHERE created_at >= ? (few distinct customer_id values)
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (lower(email));CONCURRENTLY: build and drop indexes on a live table
A plain CREATE INDEX blocks every INSERT, UPDATE and DELETE on the table until it finishes. CONCURRENTLY scans the table twice and waits for older transactions, taking longer but letting writes continue. It cannot run inside a transaction block, and if it fails it leaves an INVALID index behind that you must drop and create again.
CREATE INDEX CONCURRENTLY orders_status_idx ON orders (status);
DROP INDEX CONCURRENTLY IF EXISTS orders_old_idx;
REINDEX INDEX CONCURRENTLY orders_status_idx; -- 12+: rebuild a bloated index online
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid; -- leftovers from failed builds indexrelid
-------------------
orders_status_idx
(1 row)Partial, expression and covering indexes
A partial index is smaller and faster when queries always filter on the same condition, and a partial unique index enforces rules such as one active row per user. An expression index only serves queries that use exactly the same expression. Casting timestamptz to date depends on the TimeZone setting, so PostgreSQL rejects it in an index; index (created_at AT TIME ZONE 'UTC')::date instead.
CREATE INDEX ON jobs (run_at) WHERE status = 'queued'; -- only the rows you query
CREATE INDEX ON customers (lower(email)); -- matches WHERE lower(email) = ?
CREATE INDEX ON orders ((created_at::date)); -- error for timestamptz: not immutable
CREATE INDEX ON orders (customer_id) INCLUDE (total, status); -- 11+: index only scans
CREATE UNIQUE INDEX ON subscriptions (user_id) WHERE cancelled_at IS NULL; -- one active subscription eachBeyond B-tree
Which index type for which query
| Type | Good for | Example |
|---|---|---|
| B-tree | =, <, >, BETWEEN, ORDER BY, LIKE 'abc%' | CREATE INDEX ON orders (created_at) |
| GIN | arrays, jsonb, full text, trigrams | CREATE INDEX ON docs USING gin (search) |
| GiST | ranges, geometry, exclusion constraints, nearest neighbour | CREATE INDEX ON bookings USING gist (during) |
| SP-GiST | points, IP ranges, non balanced data | CREATE INDEX ON hosts USING spgist (ip inet_ops) |
| BRIN | huge tables whose rows are stored roughly in column order | CREATE INDEX ON events USING brin (created_at) |
| Hash | = only | CREATE INDEX ON sessions USING hash (token) |
BRIN for append only time series
BRIN stores only the minimum and maximum value for each block range, so it is thousands of times smaller than a B-tree. It works when the physical row order follows the column, as with append only logs keyed by time, and becomes useless when rows are updated or inserted out of order.
CREATE INDEX events_created_brin ON events USING brin (created_at) WITH (pages_per_range = 64);
SELECT pg_size_pretty(pg_relation_size('events_created_brin')) AS brin,
pg_size_pretty(pg_relation_size('events_created_at_idx')) AS btree; brin | btree
-------+---------
48 kB | 2140 MB
(1 row)Keep Indexes Honest
Unused and oversized indexes
Every index slows every write to its table and takes memory in shared_buffers. idx_scan counts since the statistics were last reset, and only on this server, so check replicas too before dropping an index that reports zero scans on the primary.
SELECT s.relname AS table, s.indexrelname AS index, 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 AND NOT i.indisprimary
ORDER BY pg_relation_size(s.indexrelid) DESC; table | index | idx_scan | size
--------+--------------------+----------+--------
orders | orders_status_idx | 0 | 312 MB
events | events_payload_idx | 0 | 88 MB
(2 rows)Duplicate indexes
SELECT indrelid::regclass AS table, array_agg(indexrelid::regclass) AS duplicates
FROM pg_index
GROUP BY indrelid, indkey::text, indclass::text, coalesce(indexprs::text, ''), coalesce(indpred::text, '')
HAVING count(*) > 1;Index bloat, roughly
A freshly built B-tree has leaf pages about 90 percent full. After many updates and deletes, density can fall to half, so the index is twice the size it needs to be and caches worse. REINDEX CONCURRENTLY rebuilds it without blocking writes.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('orders_customer_created_idx'); avg_leaf_density | leaf_fragmentation
------------------+--------------------
48.32 | 31.05
(1 row)EXPLAIN & Tuning
Read a Plan
EXPLAIN and EXPLAIN ANALYZE
cost is in arbitrary planner units, first to return the first row and then all rows; rows is the estimate. With ANALYZE, actual time is in milliseconds per loop and rows is per loop too, so multiply by loops. From 18, BUFFERS is on by default with ANALYZE, actual rows show decimals, and index scans report Index Searches.
EXPLAIN SELECT * FROM orders WHERE customer_id = 12; -- estimated plan only
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 12; -- runs it, real numbers
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS) SELECT ...;
BEGIN; EXPLAIN ANALYZE DELETE FROM orders WHERE id = 1; ROLLBACK; -- ANALYZE executes writes QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------
Index Scan using orders_customer_created_idx on orders (cost=0.43..38.12 rows=31 width=64) (actual time=0.021..0.058 rows=29.00 loops=1)
Index Cond: (customer_id = 12)
Buffers: shared hit=33
Index Searches: 1
Planning Time: 0.118 ms
Execution Time: 0.081 ms
(6 rows)The node types, in plain words
| Node | Means | Worry when |
|---|---|---|
| Seq Scan | reads the whole table | the table is large and Rows Removed by Filter is huge |
| Index Scan | walks the index, fetches each row | it returns a large share of the table |
| Index Only Scan | answers from the index alone | Heap Fetches is high: VACUUM the table |
| Bitmap Heap Scan | collects matching pages, then reads them in order | lossy blocks appear: raise work_mem |
| Nested Loop | for each outer row, look up the inner side | the inner side is a Seq Scan with many loops |
| Hash Join | builds a hash of one side | Batches is above 1: work_mem too small |
| Merge Join | walks two sorted inputs | an explicit Sort feeds it on a big input |
| Sort | sorts in memory or on disk | Sort Method: external merge |
Paste a plan into the toolbox
The toolbox flags the usual suspects: sequential scans that discard most rows, sorts and hashes that spill to disk, estimates that are off by more than ten times, nested loops over sequential scans, missing parallel workers and index only scans with stale visibility maps, and reports the step that took the most time on its own.
EXPLAIN (ANALYZE, BUFFERS) SELECT c.id, sum(o.total)
FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= '2026-01-01' GROUP BY c.id ORDER BY 2 DESC;
-- copy the whole output into the SQL toolbox at the top and press "read EXPLAIN"Find the Slow Queries
pg_stat_statements: the most expensive queries
Sort by total time, not mean time: a 2 ms query run a million times costs more than a 2 second report run twice a day. pg_stat_statements normalizes constants into $1 placeholders so repeated queries group together; it is the first thing to install on any server you care about.
-- postgresql.conf: shared_preload_libraries = 'pg_stat_statements' (restart)
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT round(total_exec_time::numeric / 1000, 1) AS total_s, calls,
round(mean_exec_time::numeric, 2) AS mean_ms, rows,
round(100 * shared_blks_hit::numeric / nullif(shared_blks_hit + shared_blks_read, 0), 1) AS hit_pct,
left(query, 60) AS query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
SELECT pg_stat_statements_reset(); total_s | calls | mean_ms | rows | hit_pct | query
---------+--------+---------+--------+---------+--------------------------------------------------------------
1840.2 | 912044 | 2.02 | 912044 | 99.8 | SELECT * FROM orders WHERE customer_id = $1 ORDER BY created
611.9 | 288 | 2124.62 | 288 | 41.3 | SELECT date_trunc($1, created_at), sum(total) FROM orders GR
(2 rows)Log slow queries and their plans
auto_explain writes the plan of every statement slower than the threshold to the server log, which catches the queries that are only slow with production data or parameters. log_analyze adds real row counts and timings at a small overhead on every query.
ALTER SYSTEM SET log_min_duration_statement = '500ms';
ALTER SYSTEM SET auto_explain.log_min_duration = '1s';
ALTER SYSTEM SET session_preload_libraries = 'auto_explain';
ALTER SYSTEM SET auto_explain.log_analyze = on;
SELECT pg_reload_conf();Prepared statements and the plan cache
After five executions PostgreSQL may switch a prepared statement to a generic plan that ignores the parameter value, which is bad for skewed data where one customer has millions of orders and most have ten. plan_cache_mode lets you force custom or generic plans per session or role when a driver's prepared statements behave differently from your psql tests.
PREPARE by_customer(bigint) AS SELECT * FROM orders WHERE customer_id = $1;
EXECUTE by_customer(12);
EXPLAIN EXECUTE by_customer(12);
SET plan_cache_mode = force_custom_plan; -- 12+: always plan with the actual value
DEALLOCATE by_customer;Progress of long running maintenance
SELECT relid::regclass, phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS pct
FROM pg_stat_progress_create_index; -- CREATE INDEX and REINDEX
SELECT relid::regclass, phase, round(100.0 * sample_blks_scanned / nullif(sample_blks_total, 0), 1) AS pct
FROM pg_stat_progress_analyze; relid | phase | pct
--------+--------------------------------+------
orders | building index: scanning table | 63.8
(1 row)Help the Planner
Statistics: ANALYZE, targets and extended statistics
The planner estimates rows from per column statistics and assumes columns are independent, so WHERE city = 'Cluj' AND zip = '400001' is underestimated by the size of the correlation. CREATE STATISTICS teaches it about such dependencies. Bad estimates are behind most bad plans, so fix estimates before reaching for planner settings.
ANALYZE orders;
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000; -- more detail for a skewed column
CREATE STATISTICS orders_city_zip (dependencies, ndistinct) ON city, zip FROM addresses;
ANALYZE addresses;
SELECT attname, n_distinct, most_common_vals FROM pg_stats WHERE tablename = 'orders' AND attname = 'status'; attname | n_distinct | most_common_vals
---------+------------+-----------------------------
status | 4 | {shipped,paid,refunded,new}
(1 row)Test a plan by switching things off, in one session only
The enable_ settings do not forbid a plan type; they add a huge cost to it, which is useful to compare the chosen plan with the alternative. Never set them globally as a fix. PostgreSQL has no query hints in core; the pg_hint_plan extension adds them, and 19 adds pg_plan_advice for stabilizing plans.
SET enable_seqscan = off; -- would it use the index if forced to?
SET enable_nestloop = off;
SET work_mem = '256MB'; -- would the sort fit in memory?
SET random_page_cost = 1.1; -- SSD storage
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;
RESET ALL;VACUUM & Autovacuum
Why VACUUM Exists
Dead rows and what VACUUM does
An UPDATE in PostgreSQL writes a new row version and marks the old one dead; a DELETE only marks it. VACUUM makes the space of dead versions reusable, updates the visibility map for index only scans and freezes old rows. Plain VACUUM does not shrink the file and runs alongside normal traffic; autovacuum does it for you when it is not held back.
SELECT 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_autovacuum, last_autoanalyze
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 5;
VACUUM (VERBOSE, ANALYZE) orders; relname | n_live_tup | n_dead_tup | dead_pct | last_autovacuum
----------+------------+------------+----------+----------------------------
sessions | 84012 | 912440 | 91.6 | 2026-09-22 03:14:09.112+00
orders | 1204331 | 61220 | 4.8 | 2026-09-29 09:48:51.402+00
(2 rows)VACUUM FULL versus online alternatives
VACUUM FULL and CLUSTER build a new copy of the table and lock it against reads and writes until done, which on a large table is an outage. pg_repack and pg_squeeze do the same rewrite while the table stays usable. PostgreSQL 19 adds a REPACK command that replaces both, and REPACK ... CONCURRENTLY rebuilds without the long lock; reviewers flagged the concurrent option as at risk late in the beta, so check the final 19 release notes.
VACUUM FULL orders; -- rewrites the table compactly; ACCESS EXCLUSIVE lock throughout
CLUSTER orders USING orders_customer_created_idx; -- rewrite in index order; also locks
-- online, with an extension: pg_repack --table=orders --no-order -d shopTune Autovacuum
Per table settings for big, busy tables
By default autovacuum starts when dead rows exceed 20 percent of the table, which for a 500 million row table means 100 million dead rows first. Lowering the scale factor per table makes it run earlier and finish faster. Raising the cost limit lets it work harder on modern disks instead of throttling itself.
ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.01, autovacuum_vacuum_threshold = 10000);
ALTER TABLE events SET (autovacuum_analyze_scale_factor = 0.02);
ALTER TABLE events SET (autovacuum_vacuum_insert_scale_factor = 0.05); -- 13+: insert only tables too
-- postgresql.conf, for the whole server
autovacuum_max_workers = 5
autovacuum_vacuum_cost_limit = 2000 -- default -1 uses vacuum_cost_limit (200): too slow for SSDs
autovacuum_naptime = 30sWhat is autovacuum doing right now
SELECT p.pid, p.relid::regclass AS table, p.phase,
round(100.0 * p.heap_blks_scanned / nullif(p.heap_blks_total, 0), 1) AS pct,
now() - a.xact_start AS running
FROM pg_stat_progress_vacuum p JOIN pg_stat_activity a USING (pid); pid | table | phase | pct | running
-------+--------+---------------+------+----------
51022 | events | scanning heap | 38.2 | 00:04:12
(1 row)What stops VACUUM from cleaning up
VACUUM can only remove row versions that no running transaction could still see. One session idle in transaction for six hours, an abandoned replication slot, a forgotten prepared transaction or a replica with hot_standby_feedback running a long query holds that horizon back for the whole cluster, and dead rows pile up in every table.
SELECT pid, usename, state, now() - xact_start AS age, left(query, 50) AS query
FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY xact_start LIMIT 5;
SELECT slot_name, active, age(xmin) AS xmin_age FROM pg_replication_slots;
SELECT gid, prepared, owner FROM pg_prepared_xacts;Transaction ID Wraparound
How far from wraparound is each database
Transaction ids are 32 bits, so every row must eventually be frozen by VACUUM before its id is two billion transactions old. Autovacuum starts aggressive anti wraparound vacuums at autovacuum_freeze_max_age (200 million by default). If they cannot keep up, PostgreSQL finally stops accepting writes to protect the data, so alert well before 50 percent.
SELECT datname, age(datfrozenxid) AS xid_age,
round(100.0 * age(datfrozenxid) / 2147483648, 1) AS pct_to_wraparound
FROM pg_database ORDER BY 2 DESC;
SELECT relname, age(relfrozenxid) FROM pg_class WHERE relkind = 'r' ORDER BY 2 DESC LIMIT 5; datname | xid_age | pct_to_wraparound
----------+-----------+-------------------
shop | 612044181 | 28.5
postgres | 48213410 | 2.2
(2 rows)HOT updates and fillfactor
A heap only tuple (HOT) update puts the new row version on the same page and skips updating indexes, which is much cheaper, but only when no indexed column changed and the page has free space. A lower fillfactor on frequently updated tables leaves that space; an index on a column that changes on every update prevents HOT entirely.
SELECT relname, n_tup_upd, 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_upd DESC LIMIT 5;
ALTER TABLE counters SET (fillfactor = 80); -- leave room on each page for new row versionsServer Config
Read and Change Settings
SHOW, SET, ALTER SYSTEM, reload
Settings apply in layers: postgresql.conf, then postgresql.auto.conf written by ALTER SYSTEM, then per database, per role and per role in database, then SET in the session. Some settings such as shared_buffers and max_connections only change on restart; most others take effect on reload.
SHOW work_mem;
SET work_mem = '64MB'; -- this session
SET LOCAL work_mem = '256MB'; -- this transaction only
ALTER SYSTEM SET work_mem = '32MB'; -- writes postgresql.auto.conf
SELECT pg_reload_conf();
ALTER DATABASE shop SET statement_timeout = '30s';
ALTER ROLE reporting SET work_mem = '256MB'; work_mem
----------
4MB
(1 row)Where a setting came from, and what needs a restart
context tells you how a setting can change: postmaster needs a restart, sighup a reload, user and superuser can be set per session. shared_buffers is reported in 8 kB pages, so 16384 means 128 MB; the unit column says which unit the number is in.
SELECT name, setting, unit, source, sourcefile, pending_restart
FROM pg_settings WHERE source NOT IN ('default', 'override') ORDER BY name;
SELECT name, setting, context FROM pg_settings WHERE name IN ('shared_buffers', 'work_mem', 'max_connections');
SELECT * FROM pg_file_settings WHERE error IS NOT NULL; -- typos in the config files name | setting | context
-----------------+---------+------------
max_connections | 100 | postmaster
shared_buffers | 16384 | postmaster
work_mem | 4096 | user
(3 rows)Lock ALTER SYSTEM down
When Ansible, Kubernetes operators or Patroni own postgresql.conf, a superuser's ALTER SYSTEM writes settings into postgresql.auto.conf that silently override them. allow_alter_system = off makes ALTER SYSTEM fail instead; it is a guard rail, not a security boundary, since superusers can still change files.
allow_alter_system = off # postgresql.conf, 17+: configuration stays under config management
SHOW allow_alter_system;Managed PostgreSQL
What changes on RDS, Cloud SQL and Azure
| Topic | Amazon RDS and Aurora | Google Cloud SQL | Azure Flexible Server |
|---|---|---|---|
| admin role | rds_superuser | cloudsqlsuperuser | azure_pg_admin |
| settings | parameter groups | database flags | server parameters |
| extensions | SHOW rds.extensions lists the allowed ones | fixed allow list in the docs | allow list in azure.extensions |
| server files, COPY FROM a path | not available: use \copy or aws_s3 | not available: use \copy | not available: use \copy |
| superuser only rows on this page | hidden by managed mode | hidden by managed mode | hidden by managed mode |
Habits that transfer to any managed service
You do not get a real superuser, shell access, or the data directory on a managed service, so anything that reads server files, loads arbitrary extensions or edits pg_hba.conf goes through the provider's console instead. The managed mode switch in the toolbar hides the rows on this page that need those powers.
SELECT current_setting('server_version'), current_setting('max_connections');
SELECT name, setting, source FROM pg_settings WHERE source <> 'default' ORDER BY name;
SELECT extname, extversion FROM pg_extension ORDER BY 1;
\copy big_table TO 'big_table.csv' WITH (FORMAT csv, HEADER true) -- instead of server side COPYThe Settings That Matter
Memory and I/O on a dedicated server
The command builder at the top computes these from RAM, CPU count and workload. The trap is work_mem: a complex query can use several multiples of it, once per sort and hash, and every connection can run such a query, so a large value times many connections can exhaust memory.
shared_buffers = 4GB # about 25% of RAM (restart)
effective_cache_size = 12GB # about 75% of RAM: a planner hint, allocates nothing
work_mem = 32MB # per sort or hash node, per query, per connection
maintenance_work_mem = 1GB # VACUUM, CREATE INDEX
random_page_cost = 1.1 # SSD; the default 4 assumes spinning disks
effective_io_concurrency = 200 # SSD
max_wal_size = 8GB # fewer, larger checkpoints
huge_pages = try # large shared_buffersConnections and pooling
Each PostgreSQL connection is a separate server process with its own memory, so thousands of mostly idle connections waste resources and slow snapshots. A pooler such as PgBouncer in transaction mode shares a few dozen server connections among thousands of clients; session state such as SET, temporary tables and session advisory locks does not survive between transactions in that mode.
SELECT count(*), state FROM pg_stat_activity GROUP BY state;
SHOW max_connections;
-- pgbouncer.ini
[databases]
shop = host=127.0.0.1 port=5432 dbname=shop
[pgbouncer]
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 40 count | state
-------+---------------------
38 | active
412 | idle
6 | idle in transaction
(3 rows)Logging worth turning on
log_min_duration_statement = 500ms
log_checkpoints = on # default on since 15
log_connections = on
log_lock_waits = on
log_temp_files = 0 # every sort or hash that spilled to disk
log_autovacuum_min_duration = 1s
log_line_prefix = '%m [%p] %q%u@%d 'Asynchronous I/O in 18
PostgreSQL 18 reads ahead asynchronously for sequential scans, bitmap heap scans and VACUUM, instead of waiting for one block at a time, which helps most on cloud volumes with high latency. worker mode works everywhere; io_uring avoids the extra processes on Linux; sync restores the old behaviour for comparison.
SHOW io_method; -- worker (default), io_uring or sync
ALTER SYSTEM SET io_method = 'io_uring'; -- Linux builds with liburing; restart
SHOW io_workers; -- worker mode: background I/O processes, default 3
SELECT * FROM pg_aios; -- in flight asynchronous I/OPartitioning
Declarative Partitioning
Range partitions by month
A primary key or unique constraint on a partitioned table must include the partition key, because uniqueness is enforced per partition. The default partition catches rows that fit nowhere else, but it must be scanned whenever you add a partition that overlaps it, so keep it empty and alert when it is not.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
created_at timestamptz NOT NULL,
payload jsonb,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_09 PARTITION OF events FOR VALUES FROM ('2026-09-01') TO ('2026-10-01');
CREATE TABLE events_2026_10 PARTITION OF events FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
CREATE TABLE events_default PARTITION OF events DEFAULT;
CREATE INDEX ON events (created_at); -- created on every partition, present and future
\d+ events Partitioned table "public.events"
Partition key: RANGE (created_at)
Indexes:
"events_pkey" PRIMARY KEY, btree (id, created_at)
"events_created_at_idx" btree (created_at)
Partitions: events_2026_09 FOR VALUES FROM ('2026-09-01 00:00:00+00') TO ('2026-10-01 00:00:00+00'),
events_2026_10 FOR VALUES FROM ('2026-10-01 00:00:00+00') TO ('2026-11-01 00:00:00+00'),
events_default DEFAULTList and hash partitioning
CREATE TABLE customers_by_region (id bigint, region text NOT NULL, name text) PARTITION BY LIST (region);
CREATE TABLE customers_eu PARTITION OF customers_by_region FOR VALUES IN ('RO', 'DE', 'FR');
CREATE TABLE customers_us PARTITION OF customers_by_region FOR VALUES IN ('US', 'CA');
CREATE TABLE sessions (id uuid, data jsonb) PARTITION BY HASH (id);
CREATE TABLE sessions_0 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0);
INSERT INTO customers_by_region VALUES (1, 'JP', 'Kenji');ERROR: no partition of relation "customers_by_region" found for row
DETAIL: Partition key of the failing row contains (region) = (JP).Retention: drop old data instantly
Dropping a partition removes a month of data in milliseconds with no dead rows and no VACUUM, which is the main reason to partition time series. Attaching a table you loaded separately needs a scan to validate its rows, unless a matching CHECK constraint already proves they fit.
ALTER TABLE events DETACH PARTITION events_2025_09 CONCURRENTLY; -- 14+: no lock on queries of events
DROP TABLE events_2025_09;
ALTER TABLE events ATTACH PARTITION events_2026_11 FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');Check that pruning happens
Partition pruning only works when the WHERE clause constrains the partition key with values the planner or executor can compare, so a query filtering on date(created_at) or on another column reads every partition. Look for a single partition in the plan; with thousands of partitions, planning time itself becomes the cost.
EXPLAIN SELECT count(*) FROM events WHERE created_at >= '2026-09-15' AND created_at < '2026-09-20';
SELECT tableoid::regclass AS partition, count(*) FROM events GROUP BY 1; QUERY PLAN
--------------------------------------------------------------------------------------------------
Aggregate (cost=1804.12..1804.13 rows=1 width=8)
-> Index Only Scan using events_2026_09_created_at_idx on events_2026_09 events
Index Cond: ((created_at >= '2026-09-15 00:00:00+00'::timestamp with time zone) AND ...)Merge or split partitions today
Copy, detach and attach in one transaction, so readers see either the old partitions or the new one. ALTER TABLE ... MERGE PARTITIONS and SPLIT PARTITION were committed for PostgreSQL 19 but reverted in August 2026 before release because of correctness problems, so this manual route remains the way.
BEGIN;
CREATE TABLE events_2026_q1 (LIKE events INCLUDING ALL);
INSERT INTO events_2026_q1 SELECT * FROM events WHERE created_at >= '2026-01-01' AND created_at < '2026-04-01';
ALTER TABLE events DETACH PARTITION events_2026_01;
ALTER TABLE events DETACH PARTITION events_2026_02;
ALTER TABLE events DETACH PARTITION events_2026_03;
ALTER TABLE events ATTACH PARTITION events_2026_q1 FOR VALUES FROM ('2026-01-01') TO ('2026-04-01');
COMMIT;
DROP TABLE events_2026_01, events_2026_02, events_2026_03;pg_partman: create and drop time partitions automatically
Partitions for next month must exist before the first row arrives, or inserts land in the default partition or fail. pg_partman creates them ahead of time with premake and drops expired ones under a retention policy, which is the part people forget to automate.
CREATE EXTENSION IF NOT EXISTS pg_partman;
SELECT partman.create_parent(p_parent_table => 'public.events', p_control => 'created_at', p_interval => '1 month', p_premake => 3);
UPDATE partman.part_config SET retention = '12 months', retention_keep_table = false WHERE parent_table = 'public.events';
SELECT partman.run_maintenance(); -- schedule it, for example with pg_cron every hourFunctions & PL/pgSQL
Functions
A SQL function in one line
The RETURN form, added in 14, stores the function body parsed rather than as a string, so dependencies are tracked and the planner can inline simple SQL functions into the calling query. Mark functions IMMUTABLE only when the result depends on nothing but the arguments; STABLE for functions that read tables; VOLATILE, the default, for anything else.
CREATE OR REPLACE FUNCTION price_with_vat(p numeric, country text DEFAULT 'RO')
RETURNS numeric LANGUAGE sql IMMUTABLE PARALLEL SAFE
RETURN round(p * CASE country WHEN 'RO' THEN 1.21 WHEN 'DE' THEN 1.19 ELSE 1.20 END, 2);
SELECT name, price_with_vat(price) FROM products;
SELECT price_with_vat(100, country => 'DE'); price_with_vat
----------------
119.00
(1 row)PL/pgSQL: variables, IF, loops, RETURN QUERY
The body between the dollar quotes is a string that PL/pgSQL parses at first call, so a typo in a column name only shows up when that line runs. Qualify columns with a table alias inside functions that RETURNS TABLE, because the output column names are variables too and an unqualified status would be ambiguous.
CREATE OR REPLACE FUNCTION customer_summary(p_customer bigint)
RETURNS TABLE (status text, orders bigint, revenue numeric)
LANGUAGE plpgsql STABLE AS $$
DECLARE
v_exists boolean;
BEGIN
SELECT EXISTS (SELECT 1 FROM customers WHERE id = p_customer) INTO v_exists;
IF NOT v_exists THEN
RAISE EXCEPTION 'customer % not found', p_customer USING ERRCODE = 'no_data_found';
END IF;
RETURN QUERY
SELECT o.status, count(*), sum(o.total)
FROM orders o WHERE o.customer_id = p_customer
GROUP BY o.status;
END;
$$;
SELECT * FROM customer_summary(12); status | orders | revenue
---------+--------+---------
paid | 2 | 274.75
shipped | 1 | 410.00
(2 rows)Catch errors and report details
A block with an EXCEPTION clause sets up a subtransaction every time it is entered, which costs noticeably inside tight loops, and consumes transaction ids. For the get or create pattern, INSERT ... ON CONFLICT DO NOTHING followed by a SELECT is cheaper than catching unique_violation.
CREATE OR REPLACE FUNCTION safe_insert_tag(p_name text) RETURNS bigint LANGUAGE plpgsql AS $$
DECLARE v_id bigint; v_msg text; v_state text;
BEGIN
INSERT INTO tags (name) VALUES (p_name) RETURNING id INTO v_id;
RETURN v_id;
EXCEPTION
WHEN unique_violation THEN
SELECT id INTO v_id FROM tags WHERE name = p_name;
RETURN v_id;
WHEN OTHERS THEN
GET STACKED DIAGNOSTICS v_msg = MESSAGE_TEXT, v_state = RETURNED_SQLSTATE;
RAISE WARNING 'tag insert failed: % (%)', v_msg, v_state;
RETURN NULL;
END;
$$;Procedures, DO Blocks and Dynamic SQL
Procedures can COMMIT between batches
Functions always run inside the caller's transaction; procedures, called with CALL, may COMMIT and ROLLBACK themselves, so one call can process a large backlog in small committed batches. CALL must not itself run inside an explicit transaction block for that to work.
CREATE OR REPLACE PROCEDURE purge_events(p_days int)
LANGUAGE plpgsql AS $$
DECLARE n int;
BEGIN
LOOP
DELETE FROM events WHERE ctid IN (
SELECT ctid FROM events WHERE created_at < now() - make_interval(days => p_days) LIMIT 5000);
GET DIAGNOSTICS n = ROW_COUNT;
COMMIT;
EXIT WHEN n = 0;
END LOOP;
END;
$$;
CALL purge_events(90);DO: run a block of code once
DO $$
DECLARE r record;
BEGIN
FOR r IN SELECT schemaname, tablename FROM pg_tables WHERE schemaname = 'staging' LOOP
EXECUTE format('ANALYZE %I.%I', r.schemaname, r.tablename);
RAISE NOTICE 'analyzed %.%', r.schemaname, r.tablename;
END LOOP;
END;
$$;NOTICE: analyzed staging.products
NOTICE: analyzed staging.orders
DODynamic SQL without injection
Identifiers go through %I, literals through %L or, better, as parameters with USING, which keeps the plan reusable and makes injection impossible. Never concatenate a value from outside into SQL text, and never pass a type name from user input through %s without checking it against a list.
EXECUTE format('SELECT count(*) FROM %I.%I WHERE status = $1', p_schema, p_table)
INTO v_count USING p_status;
EXECUTE format('ALTER TABLE %I ADD COLUMN %I %s', p_table, p_column, 'text');SECURITY DEFINER done safely
A SECURITY DEFINER function runs with its owner's privileges, so a caller who can put objects earlier in the search_path could hijack unqualified names. Pin search_path on the function, qualify table names, and revoke the default EXECUTE grant to PUBLIC before granting it to specific roles.
CREATE OR REPLACE FUNCTION reset_password(p_user bigint, p_hash text) RETURNS void
LANGUAGE sql SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
BEGIN ATOMIC
UPDATE public.users SET password_hash = p_hash WHERE id = p_user;
END;
REVOKE ALL ON FUNCTION reset_password(bigint, text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION reset_password(bigint, text) TO app;Views & Triggers
Views
Views, updatable views and CHECK OPTION
A view that selects from one table without aggregates is automatically updatable. WITH CHECK OPTION rejects inserts and updates through the view that would produce rows the view cannot see. By default a view accesses its tables with the view owner's privileges, which bypasses row level security for the caller; security_invoker, added in 15, makes it use the caller's.
CREATE OR REPLACE VIEW active_customers AS
SELECT id, name, email, country FROM customers WHERE deleted_at IS NULL;
CREATE VIEW ro_customers WITH (security_invoker = true) AS -- 15+: caller's privileges and RLS
SELECT * FROM customers WHERE country = 'RO'
WITH CHECK OPTION;
UPDATE active_customers SET email = 'new@example.com' WHERE id = 12; -- simple views are updatableMaterialized views for expensive reports
A materialized view stores the query result like a table and is only as fresh as its last refresh. A plain REFRESH locks it against reads while it runs; CONCURRENTLY keeps it readable and swaps in the changes, but needs a unique index on the view. Schedule the refresh with cron or pg_cron.
CREATE MATERIALIZED VIEW daily_revenue AS
SELECT created_at::date AS day, count(*) AS orders, sum(total) AS revenue
FROM orders GROUP BY 1
WITH DATA;
CREATE UNIQUE INDEX ON daily_revenue (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue;REFRESH MATERIALIZED VIEWTriggers
Keep updated_at current
A BEFORE trigger can change the row before it is written by modifying NEW and returning it; returning NULL skips the row. The WHEN clause avoids touching rows where nothing actually changed, so an UPDATE that sets the same values does not bump the timestamp.
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER orders_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION set_updated_at();An audit trail in jsonb
CREATE TABLE audit_log (id bigint GENERATED ALWAYS AS IDENTITY, tbl text, op text, row_id bigint,
old jsonb, new jsonb, by_user text DEFAULT current_user, at timestamptz DEFAULT now());
CREATE OR REPLACE FUNCTION audit() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO audit_log (tbl, op, row_id, old, new)
VALUES (TG_TABLE_NAME, TG_OP, coalesce(NEW.id, OLD.id),
CASE WHEN TG_OP <> 'INSERT' THEN to_jsonb(OLD) END,
CASE WHEN TG_OP <> 'DELETE' THEN to_jsonb(NEW) END);
RETURN NULL;
END;
$$;
CREATE TRIGGER orders_audit AFTER INSERT OR UPDATE OR DELETE ON orders FOR EACH ROW EXECUTE FUNCTION audit();Statement triggers with transition tables
A row trigger fires once per row, which adds up on bulk loads. A statement trigger with a transition table fires once per statement and sees every affected row as a table, so aggregate bookkeeping becomes one set based query.
CREATE TRIGGER orders_bulk_stats
AFTER INSERT ON orders
REFERENCING NEW TABLE AS inserted
FOR EACH STATEMENT EXECUTE FUNCTION refresh_counts();
-- inside refresh_counts(): SELECT customer_id, count(*) FROM inserted GROUP BY 1LISTEN and NOTIFY
Notifications are delivered only when the sending transaction commits and only to sessions currently listening, so they are a wake up signal, not a durable queue; pair them with a table the listener reads. Payloads are limited to 8000 bytes. LISTEN does not work through PgBouncer in transaction mode.
LISTEN order_events;
CREATE OR REPLACE FUNCTION notify_order() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM pg_notify('order_events', json_build_object('id', NEW.id, 'status', NEW.status)::text);
RETURN NULL;
END;
$$;
CREATE TRIGGER orders_notify AFTER INSERT OR UPDATE OF status ON orders FOR EACH ROW EXECUTE FUNCTION notify_order();Asynchronous notification "order_events" with payload "{"id" : 10042, "status" : "paid"}" received from server process with PID 48213.Event triggers: react to DDL
CREATE OR REPLACE FUNCTION log_ddl() RETURNS event_trigger LANGUAGE plpgsql AS $$
DECLARE r record;
BEGIN
FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() LOOP
RAISE NOTICE 'DDL: % on %', r.command_tag, r.object_identity;
END LOOP;
END;
$$;
CREATE EVENT TRIGGER track_ddl ON ddl_command_end EXECUTE FUNCTION log_ddl();Roles & Security
Roles and Grants
Roles, users and group roles
Users and groups are the same thing in PostgreSQL: a role with LOGIN can connect, and any role can be granted to another. Prefer \password in psql over typing PASSWORD in SQL, which may end up in the server log and in shell history. A role that owns objects cannot be dropped until REASSIGN OWNED BY and DROP OWNED BY clean up after it.
CREATE ROLE app LOGIN PASSWORD 'change-me' CONNECTION LIMIT 50; -- CREATE USER = CREATE ROLE ... LOGIN
CREATE ROLE readers NOLOGIN; -- a group
GRANT readers TO analyst;
ALTER ROLE app WITH PASSWORD 'new-secret' VALID UNTIL '2027-12-31';
ALTER ROLE app SET statement_timeout = '15s';
DROP ROLE IF EXISTS old_app;
\du List of roles
Role name | Attributes
-----------+------------------------------------------------------------
analyst |
app | 50 connections
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS
readers | Cannot loginGRANT on tables, schemas and databases
A role needs permission at every level: CONNECT on the database, USAGE on the schema, then privileges on the table. ON ALL TABLES only covers tables that exist now; tables created later need ALTER DEFAULT PRIVILEGES or another GRANT, which is the most common reason an application suddenly gets permission denied after a migration.
GRANT CONNECT ON DATABASE shop TO app;
GRANT USAGE ON SCHEMA public TO app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app;
GRANT SELECT (id, name, email) ON customers TO support; -- column privileges
REVOKE DELETE ON orders FROM app;
\dp ordersDefault privileges for tables created later
Default privileges apply to objects created by a specific role, the one named in FOR ROLE or the one running the statement. If migrations run as migrator, the default privileges must be defined for migrator; defining them as postgres does nothing for tables migrator creates.
ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app;
ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO app;
\ddpPredefined roles instead of superuser
| Role | Grants | Since |
|---|---|---|
pg_read_all_data | SELECT on every table, view and sequence | 14 |
pg_write_all_data | INSERT, UPDATE, DELETE everywhere | 14 |
pg_monitor | read all monitoring views and pg_stat_statements | 10 |
pg_signal_backend | cancel and terminate other sessions (not superusers) | 9.6 |
pg_checkpoint | run CHECKPOINT | 15 |
pg_create_subscription | create logical replication subscriptions | 16 |
pg_maintain | VACUUM, ANALYZE, REINDEX, REFRESH, CLUSTER, LOCK on any table | 17 |
pg_read_server_files | COPY FROM server files | 11 |
Row Level Security
One database, many tenants
USING filters which existing rows a role can see or change, WITH CHECK validates new and updated rows. Superusers and roles with BYPASSRLS ignore policies, and the owner does too unless FORCE is set. With a connection pool, use SET LOCAL inside each transaction so one request's tenant id never leaks into the next.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY; -- apply to the table owner too
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::bigint)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);
SET app.tenant_id = '42'; -- the application sets this per request
SELECT count(*) FROM invoices; -- only tenant 42's rows count
-------
318
(1 row)Check what a role may do
SELECT has_table_privilege('app', 'orders', 'DELETE'), has_schema_privilege('app', 'public', 'CREATE');
SELECT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_name = 'orders';
SET ROLE app; SELECT * FROM orders LIMIT 1; RESET ROLE; -- test as that role has_table_privilege | has_schema_privilege
---------------------+----------------------
f | f
(1 row)Authentication and Encryption
Client certificates instead of passwords
Certificates are hard to phish and easy to rotate from a secrets manager, which makes them a good fit for services talking to the database. With cert alone the certificate's common name must match the role, or a map in pg_ident.conf translates it; clientcert=verify-full on a scram line demands both.
# pg_hba.conf
hostssl all all 10.0.0.0/16 cert # the certificate CN must equal the role
hostssl all all 0.0.0.0/0 scram-sha-256 clientcert=verify-full # password and certificate
# postgresql.conf: ssl_ca_file = 'root.crt' (the CA that signs client certificates)
psql "host=db1 dbname=shop user=app sslmode=verify-full sslcert=app.crt sslkey=app.key sslrootcert=root.crt"pgAudit: who changed what
Normal logging records statements but not reliably who touched which object; pgAudit writes structured audit lines for the classes you choose, which compliance frameworks such as SOC 2 and PCI DSS ask for. Logging every read is expensive, so enable read auditing per role or per object rather than globally.
-- postgresql.conf: shared_preload_libraries = 'pgaudit' (restart)
CREATE EXTENSION pgaudit;
ALTER SYSTEM SET pgaudit.log = 'ddl, role, write';
ALTER ROLE analyst SET pgaudit.log = 'read';
SELECT pg_reload_conf();AUDIT: SESSION,1,1,DDL,ALTER TABLE,,,ALTER TABLE orders ADD COLUMN note text,<not logged>SCRAM passwords, and finding md5 leftovers
md5 password authentication is deprecated as of 18, with warnings after md5 logins in 19, and will be removed. Moving a role means setting its password again while password_encryption is scram-sha-256, then changing its pg_hba.conf lines from md5 to scram-sha-256. Reading pg_authid needs superuser.
SHOW password_encryption; -- scram-sha-256, the default since 14
SELECT rolname FROM pg_authid WHERE rolpassword LIKE 'md5%';
SET password_encryption = 'scram-sha-256';
\password app -- re-enter to store a SCRAM hashRequire TLS
-- postgresql.conf
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_min_protocol_version = 'TLSv1.2'
-- pg_hba.conf: hostssl lines only, and a final reject for plain host
SELECT ssl, version, cipher FROM pg_stat_ssl JOIN pg_stat_activity USING (pid) WHERE pid = pg_backend_pid(); ssl | version | cipher
-----+---------+------------------------
t | TLSv1.3 | TLS_AES_256_GCM_SHA384
(1 row)OAuth sign-in, 18+
PostgreSQL 18 can accept OAuth 2.0 bearer tokens, so people sign in to psql with the company's single sign on instead of a database password. Core ships the protocol support; token validation comes from a validator module, so check what your identity provider or managed service supports before planning around it.
# pg_hba.conf
host all all 0.0.0.0/0 oauth issuer="https://login.example.com" scope="openid postgres"
# postgresql.conf: a validator module from your identity provider or a third party
oauth_validator_libraries = 'my_validator'Backup & Restore
Logical Backups
pg_dump and pg_restore
pg_dump takes a consistent snapshot without blocking writes, but it only covers one database and never the roles, which live in the cluster; dump those with pg_dumpall --globals-only. The custom and directory formats let pg_restore run in parallel and restore single objects, so prefer them over plain SQL for anything but small databases. The command builder at the top writes the full command set.
pg_dump -Fc -d shop -f shop.dump # custom format: compressed, selective restore
pg_dump -Fd -j 8 -d shop -f shop.d # directory format: parallel dump
pg_dumpall --globals-only -f globals.sql # roles and tablespaces
createdb shop_restored
pg_restore -d shop_restored -j 8 --no-owner shop.dump
pg_restore -d shop_restored -t orders --data-only shop.dump # one table$ pg_restore -l shop.dump | head -5
;
; Archive created at 2026-09-29 03:00:02 UTC
; dbname: shop
; TOC Entries: 412
; Compression: gzipRestore only some objects
pg_restore -l shop.dump > toc.list # table of contents
# edit toc.list: comment out lines with ;
pg_restore -L toc.list -d shop_restored shop.dump
pg_restore --schema-only -f schema.sql shop.dump # just the DDL, as SQL
pg_restore -f - shop.dump | grep -i 'CREATE INDEX' # read the archive without a database218; 1259 16390 TABLE public customers app
219; 1259 16402 TABLE public orders app
;3456; 0 16402 TABLE DATA public orders app
3457; 0 16390 TABLE DATA public customers appCopy one database to another server
Piping skips the intermediate file, which helps when disk is short, but a failure halfway leaves a partial database and nothing to retry from. For big databases, dump to a directory with -j, copy it, then restore with -j.
pg_dump -Fc -d shop -h old-db | pg_restore -h new-db -d shop --no-owner
pg_dump -d shop -h old-db | psql -h new-db -d shop -v ON_ERROR_STOP=1Three Ways to Back Up
pg_dump: logical, one database, portable
Portable across major versions and architectures, restorable table by table, and fine up to a few hundred gigabytes. It captures one moment, not the changes after it, and restoring a large dump takes hours because every index is rebuilt.
pg_dump -Fc -d shop -f shop-$(date +%F).dump
pg_restore -d shop_restored -j 8 shop-2026-09-29.dumppg_basebackup: a physical copy of the whole cluster
Copies the data files of every database at the speed of the disk, and with archived WAL it restores to any point in time. It only restores into the same major version and platform, and retention, compression and verification are left to you.
pg_basebackup -h db1 -U replicator -D /backups/base -X stream -P --checkpoint=fastwaiting for checkpoint
412088/412088 kB (100%), 1/1 tablespacepgBackRest: physical backups with retention and PITR
pgBackRest adds what production needs on top of physical backups: full, differential and incremental backups, parallel compression, encryption, S3 or Azure repositories, retention policies and checksums verified on every backup. Barman is the main alternative.
# /etc/pgbackrest/pgbackrest.conf
[global]
repo1-path=/var/lib/pgbackrest
repo1-retention-full=2
[shop]
pg1-path=/var/lib/postgresql/18/main
# postgresql.conf: archive_command = 'pgbackrest --stanza=shop archive-push %p'
pgbackrest --stanza=shop stanza-create
pgbackrest --stanza=shop --type=full backup
pgbackrest --stanza=shop info
pgbackrest --stanza=shop --type=time --target='2026-09-29 14:02:00+00' restorePhysical Backups and PITR
WAL archiving plus a base backup
A physical backup copies the data files while the server runs, and the archived WAL replays every change since, so you can restore to any moment, not only to the last dump. In production, use a tool such as pgBackRest or Barman, which handle compression, retention, parallelism and verification that a cp command does not.
# postgresql.conf
wal_level = replica
archive_mode = on # restart
archive_command = 'test ! -f /archive/%f && cp %p /archive/%f'
pg_basebackup -D /backups/base-2026-09-29 -X stream -P -h db1 -U replicator
pg_verifybackup /backups/base-2026-09-29waiting for checkpoint
4128812/4128812 kB (100%), 1/1 tablespace
backup successfully verifiedPoint in time recovery
Since 12 there is no recovery.conf: recovery settings live in postgresql.conf and an empty recovery.signal file tells the server to start in recovery. Pausing at the target lets you inspect the data read only before ending recovery; once promoted, the timeline changes and you cannot continue replaying past that point.
# restore the base backup into an empty data directory, then:
restore_command = 'cp /archive/%f %p'
recovery_target_time = '2026-09-29 14:02:00+00' # just before the bad DELETE
recovery_target_action = 'pause'
touch $PGDATA/recovery.signal
pg_ctl -D $PGDATA start
SELECT pg_wal_replay_resume(); -- after checking the data looks rightIncremental backups, 17+
An incremental backup copies only the blocks changed since the previous backup, using WAL summaries the server keeps when summarize_wal is on. pg_combinebackup merges a full backup and its chain of incrementals into a normal data directory ready to start.
ALTER SYSTEM SET summarize_wal = on; SELECT pg_reload_conf();
pg_basebackup -D /backups/full -h db1 -U replicator
pg_basebackup -D /backups/incr1 --incremental=/backups/full/backup_manifest -h db1 -U replicator
pg_combinebackup /backups/full /backups/incr1 -o /restore/dataReplication & HA
Streaming Replication
Build a replica
-R writes primary_conninfo into postgresql.auto.conf and creates standby.signal, so the copy starts as a streaming replica. -C -S creates a replication slot, which makes the primary keep WAL until the replica has received it; without a slot, a replica that falls far behind can find the WAL it needs already recycled.
-- on the primary
CREATE ROLE replicator LOGIN REPLICATION PASSWORD 'change-me';
-- pg_hba.conf: host replication replicator 10.0.0.0/16 scram-sha-256
# on the replica host, into an empty data directory
pg_basebackup -h db1 -U replicator -D /var/lib/postgresql/18/main -X stream -R -C -S replica1 -P
pg_ctl -D /var/lib/postgresql/18/main startLag, from both sides
-- on the primary
SELECT application_name, client_addr, state, sync_state,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS behind, replay_lag
FROM pg_stat_replication;
-- on the replica
SELECT pg_is_in_recovery(), now() - pg_last_xact_replay_timestamp() AS delay; application_name | client_addr | state | sync_state | behind | replay_lag
------------------+-------------+-----------+------------+--------+-----------------
replica1 | 10.0.3.21 | streaming | async | 48 kB | 00:00:00.001822
(1 row)Slots that silently fill the disk
An inactive slot makes the primary keep every WAL segment since the slot's consumer went away, until the disk fills and the primary stops. Alert on inactive slots and retained WAL, and set max_slot_wal_keep_size so a forgotten slot is invalidated instead; 18 adds idle_replication_slot_timeout for the same job.
SELECT slot_name, slot_type, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;
SELECT pg_drop_replication_slot('old_replica');
ALTER SYSTEM SET max_slot_wal_keep_size = '50GB'; -- 13+: cap what one slot can hold slot_name | slot_type | active | retained_wal
-------------+-----------+--------+--------------
replica1 | physical | t | 48 kB
old_replica | physical | f | 212 GB
(2 rows)Failover
Patroni: automatic failover in practice
Patroni keeps the cluster state in etcd, Consul or Kubernetes, promotes a replica when the leader stops renewing its lease, and fences the old leader so it cannot accept writes. Put HAProxy or a DNS name that follows the leader in front of it, or use libpq's target_session_attrs=read-write with all hosts listed.
patronictl -c /etc/patroni/patroni.yml list
patronictl -c /etc/patroni/patroni.yml switchover --leader db1 --candidate db2
patronictl -c /etc/patroni/patroni.yml edit-config # cluster wide postgresql settings+ Cluster: shop (7412345678901234567) -----+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+-----------+---------+-----------+----+-----------+
| db1 | 10.0.3.21 | Leader | running | 4 | |
| db2 | 10.0.3.22 | Replica | streaming | 4 | 0 |
+--------+-----------+---------+-----------+----+-----------+CloudNativePG on Kubernetes
An operator runs PostgreSQL the way an experienced DBA would inside Kubernetes: it creates the primary and replicas, handles failover, rolling minor upgrades and backups to object storage, and exposes read write and read only services. CloudNativePG is the most widely used one; Crunchy PGO, StackGres and Zalando's operator are alternatives.
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: shop-db
spec:
instances: 3
imageName: ghcr.io/cloudnative-pg/postgresql:18
storage:
size: 100Gi
postgresql:
parameters:
shared_buffers: 2GB
kubectl cnpg status shop-dbRead your own writes on a replica, PostgreSQL 19
After a user saves something on the primary, a read routed to a replica may not see it yet. WAIT FOR LSN, new in 19, blocks until the replica has replayed up to that point or the timeout passes, so the application can route reads to replicas without showing stale data right after a write. 19 was at the release candidate stage in late September 2026.
-- on the primary, after the write
SELECT pg_current_wal_insert_lsn(); -- for example 0/3F2A1B8
-- on the replica, before the read
WAIT FOR LSN '0/3F2A1B8' WITH (TIMEOUT '2s'); status
---------
success
(1 row)Promote a replica
Promotion is the easy part; making sure the old primary cannot come back and accept writes, and pointing clients at the new one, is what a failover manager such as Patroni does with a consensus store. With asynchronous replication, the last transactions committed on the old primary may not have reached the replica; synchronous replication trades commit latency for zero loss.
SELECT pg_promote(); -- on the replica; 12+
pg_ctl -D /var/lib/postgresql/18/main promote
SHOW synchronous_standby_names; -- on the primary, for synchronous replicas
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (replica1, replica2)';Logical Replication
Publish and subscribe tables
Logical replication sends row changes rather than disk blocks, so the target can be a different major version, have different indexes or only some tables, which makes it the standard tool for near zero downtime major upgrades. It does not replicate DDL, and in releases before 19 it does not replicate sequence values either, so sync those before switching over.
-- source: wal_level = logical (restart)
CREATE PUBLICATION shop_pub FOR TABLE orders, customers;
CREATE PUBLICATION paid_orders FOR TABLE orders WHERE (status = 'paid'); -- 15+: row filter
CREATE PUBLICATION eu_pub FOR TABLES IN SCHEMA eu; -- 15+
-- target: the tables must already exist
CREATE SUBSCRIPTION shop_sub
CONNECTION 'host=db1 dbname=shop user=replicator password=change-me'
PUBLICATION shop_pub;
SELECT * FROM pg_stat_subscription;Turn a physical replica into a logical one
Copying a large database for a new logical subscriber can take days; pg_createsubscriber converts an existing streaming replica, which already has the data, into a logical subscriber in minutes. Failover slots, also new in 17, let a subscription continue after the publisher's primary fails over to a standby; set failover = true at CREATE SUBSCRIPTION, or disable the subscription before changing it.
pg_createsubscriber -D /var/lib/postgresql/18/replica -P 'host=db1 dbname=shop' -d shop --publication=shop_pub --subscription=shop_sub
ALTER SUBSCRIPTION shop_sub DISABLE;
ALTER SUBSCRIPTION shop_sub SET (failover = true); -- 17+: only while the subscription is disabled
ALTER SUBSCRIPTION shop_sub ENABLE;Monitoring
What Is Running
Active queries, longest first
wait_event_type says what a busy session is waiting for: Lock means it is blocked by another session, IO means it is reading from disk, and an empty value with state active means it is using CPU. idle in transaction sessions hold locks and block VACUUM while doing nothing.
SELECT pid, usename, datname, state, wait_event_type, wait_event,
now() - query_start AS runtime, left(query, 60) AS query
FROM pg_stat_activity
WHERE state <> 'idle' AND pid <> pg_backend_pid()
ORDER BY query_start; pid | usename | datname | state | wait_event_type | wait_event | runtime | query
-------+---------+---------+--------+-----------------+---------------+----------------+--------------------------------------------
48213 | report | shop | active | IO | DataFileRead | 00:12:41.20391 | SELECT c.country, sum(o.total) FROM orders
48301 | app | shop | active | Lock | transactionid | 00:00:41.00811 | UPDATE orders SET status = 'paid' WHERE id
(2 rows)Cancel or kill a session
Always try pg_cancel_backend first: it stops the query and the client gets an error it can handle. Terminating a backend rolls back its open transaction; never kill a PostgreSQL process with kill -9 from the shell, which makes the postmaster restart every connection to guarantee shared memory is consistent.
SELECT pg_cancel_backend(48213); -- cancel the current query, keep the connection
SELECT pg_terminate_backend(48213); -- close the connection
SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE state = 'idle in transaction' AND now() - state_change > interval '10 minutes'; pg_cancel_backend
-------------------
t
(1 row)Health Numbers
Cache hit ratio, rollbacks, temp files, deadlocks
A busy OLTP database usually serves over 99 percent of reads from shared_buffers; a steady drop means the working set outgrew memory. temp_files counts sorts and hashes that spilled to disk, the signal to look at work_mem or at the queries doing big sorts.
SELECT datname,
round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS cache_hit_pct,
xact_commit, xact_rollback, deadlocks, temp_files, pg_size_pretty(temp_bytes) AS temp
FROM pg_stat_database WHERE datname = current_database(); datname | cache_hit_pct | xact_commit | xact_rollback | deadlocks | temp_files | temp
---------+---------------+-------------+---------------+-----------+------------+-------
shop | 99.42 | 418220913 | 12044 | 3 | 1812 | 38 GB
(1 row)Tables read by sequential scans
SELECT relname, seq_scan, seq_tup_read, idx_scan, n_live_tup
FROM pg_stat_user_tables
WHERE seq_scan > 0 AND n_live_tup > 100000
ORDER BY seq_tup_read DESC LIMIT 5; relname | seq_scan | seq_tup_read | idx_scan | n_live_tup
-----------+----------+--------------+-----------+------------
events | 4120 | 13588230410 | 91002 | 3298114
customers | 212 | 44529328 | 418220011 | 210044
(2 rows)I/O by backend type and checkpoints
pg_stat_io, added in 16, shows who reads and writes: client backends, autovacuum, the checkpointer or background writer, which tells you whether slow I/O comes from queries or from maintenance.
SELECT backend_type, object, context, reads, writes, extends, hits
FROM pg_stat_io WHERE reads > 0 OR writes > 0 ORDER BY reads DESC LIMIT 5;Checkpoints: timed or forced
Many requested checkpoints compared with timed ones mean max_wal_size is too small for the write load, so checkpoints run early and more often than checkpoint_timeout intends. In 17 these counters moved from pg_stat_bgwriter to pg_stat_checkpointer.
SELECT num_timed, num_requested, write_time, buffers_written FROM pg_stat_checkpointer; num_timed | num_requested | write_time | buffers_written
-----------+---------------+------------+-----------------
4120 | 388 | 91204411 | 8804213
(1 row)Is the server up
pg_isready -h db1 -p 5432
SELECT pg_postmaster_start_time(), now() - pg_postmaster_start_time() AS uptime, version();db1:5432 - accepting connectionsMajor Version Upgrades
pg_upgrade: minutes instead of a dump and restore
pg_upgrade reuses the data files and only rebuilds the system catalogs, so a large database moves to a new major version in minutes. Run --check first, stop both clusters, keep a backup, and remember extensions must be installed in the new version too.
pg_upgrade --check -b /usr/lib/postgresql/17/bin -B /usr/lib/postgresql/18/bin \
-d /var/lib/postgresql/17/main -D /var/lib/postgresql/18/main
pg_upgrade -b ... -B ... -d ... -D ... --link --jobs 8 # hard links: fast, old cluster unusable after start
vacuumdb --all --analyze-in-stages # before 18: statistics must be rebuiltUpgrading to 18: --swap and kept statistics
--swap moves the old data directories into the new cluster instead of copying or linking file by file, the fastest mode for clusters with many relations. Upgrades to 18 also keep most planner statistics, so the new cluster plans well from the first query instead of after a full ANALYZE.
pg_upgrade -b /usr/lib/postgresql/17/bin -B /usr/lib/postgresql/18/bin -d ... -D ... --swap --jobs 8
vacuumdb --all --analyze-in-stages --missing-stats-only # 18 carries planner statistics over; fill only the gapsExtensions
Manage Extensions
Install, list, update
CREATE EXTENSION installs objects into the current database only, from files that must already be present on the server; contrib extensions ship with PostgreSQL, others such as pgvector or PostGIS are separate packages. Managed services allow a fixed list, so check it before designing around an extension.
SELECT name, default_version, installed_version FROM pg_available_extensions ORDER BY name;
CREATE EXTENSION IF NOT EXISTS pgcrypto;
ALTER EXTENSION pg_stat_statements UPDATE;
\dx
DROP EXTENSION IF EXISTS hstore; List of installed extensions
Name | Version | Schema | Description
--------------------+---------+------------+----------------------------------------------------
pg_stat_statements | 1.12 | public | track planning and execution statistics of all SQL
pgcrypto | 1.3 | public | cryptographic functions
plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language
(3 rows)Popular Extensions
pgvector: similarity search on embeddings
pgvector adds a vector type and distance operators: <-> for Euclidean, <=> for cosine and <#> for negative inner product. An HNSW index makes nearest neighbour queries approximate but fast; the ORDER BY must use the same operator as the index's operator class, and LIMIT must be present for the index to be used.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE docs (id bigint PRIMARY KEY, body text, embedding vector(1536));
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);
SELECT id, body, embedding <=> $1 AS distance -- $1: the query embedding
FROM docs ORDER BY embedding <=> $1 LIMIT 5;PostGIS: distance and nearby searches
The geography type measures in meters on the Earth's surface, which is what store locators and delivery radii need; geometry is faster and planar, better for projected data. ST_MakePoint takes longitude first, then latitude, the reverse of how most people write coordinates.
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE TABLE stores (id bigint PRIMARY KEY, name text, location geography(Point, 4326));
CREATE INDEX ON stores USING gist (location);
SELECT name, round(ST_Distance(location, ST_MakePoint(23.5947, 46.7712)::geography)) AS meters
FROM stores
WHERE ST_DWithin(location, ST_MakePoint(23.5947, 46.7712)::geography, 5000)
ORDER BY location <-> ST_MakePoint(23.5947, 46.7712)::geography LIMIT 5; name | meters
-------------+--------
Cluj Center | 412
Cluj Iulius | 3140
(2 rows)pgcrypto: password hashes and random bytes
crypt with a bcrypt salt stores a slow, salted hash, so a leaked table does not reveal passwords. Hashing in the application is usually better still, because the plain password then never travels to the database or into its logs.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
UPDATE users SET password_hash = crypt('user-password', gen_salt('bf', 12)) WHERE id = 1;
SELECT id FROM users WHERE email = 'ana@example.com' AND password_hash = crypt('user-password', password_hash);
SELECT encode(gen_random_bytes(32), 'hex') AS api_token;postgres_fdw: query another PostgreSQL server
CREATE EXTENSION IF NOT EXISTS postgres_fdw;
CREATE SERVER legacy FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'old-db', dbname 'shop');
CREATE USER MAPPING FOR app SERVER legacy OPTIONS (user 'reader', password 'change-me');
CREATE SCHEMA legacy;
IMPORT FOREIGN SCHEMA public LIMIT TO (orders, customers) FROM SERVER legacy INTO legacy;
SELECT count(*) FROM legacy.orders WHERE created_at >= '2026-01-01';pg_cron: scheduled jobs inside the database
CREATE EXTENSION IF NOT EXISTS pg_cron; -- needs shared_preload_libraries = 'pg_cron'
SELECT cron.schedule('refresh-revenue', '*/15 * * * *', 'REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue');
SELECT cron.schedule('purge-sessions', '0 3 * * *', $$DELETE FROM sessions WHERE expires_at < now()$$);
SELECT jobid, jobname, schedule, active FROM cron.job;
SELECT cron.unschedule('purge-sessions'); jobid | jobname | schedule | active
-------+-----------------+--------------+--------
1 | refresh-revenue | */15 * * * * | t
2 | purge-sessions | 0 3 * * * | t
(2 rows)Small ones worth knowing
| Extension | What it adds |
|---|---|
citext | case insensitive text type, handy for emails |
pg_trgm | trigram similarity and fast LIKE with leading wildcards |
unaccent | strip accents for search |
btree_gist | scalar columns in GiST indexes and exclusion constraints |
hstore | a flat key/value type, older than jsonb |
pgstattuple | exact table and index bloat numbers |
pg_buffercache | what is in shared_buffers right now |
pg_partman | automatic creation and retention of time partitions |
pg_repack | rebuild bloated tables and indexes without long locks |
TimescaleDB | time series hypertables, compression, continuous aggregates |
PostgreSQL From Code
The Same Query in Five Languages
Python: psycopg 3
%s here is a parameter placeholder, not Python string formatting: the values travel separately from the SQL, so quotes in the data cannot change the query. psycopg 3 also supports COPY from Python objects with cur.copy(), which is far faster than executemany for bulk loads.
import psycopg
with psycopg.connect("postgresql://app@db.internal/shop?sslmode=verify-full") as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, total FROM orders WHERE customer_id = %s AND status = %s", (12, "paid"))
for order_id, total in cur.fetchall():
print(order_id, total)
cur.execute("INSERT INTO tags (name) VALUES (%s) RETURNING id", ("oak",))
tag_id = cur.fetchone()[0]
# leaving the with block commits; an exception rolls back10042 249.50
10049 199.00Node.js: node-postgres (pg)
node-postgres returns bigint and numeric values as strings, because JavaScript numbers cannot hold every value exactly; parse them deliberately, or register a type parser. A transaction must run on one client checked out from the pool; calling pool.query for BEGIN and COMMIT may send them to different connections. Always release the client in finally, or the pool slowly runs dry.
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
const { rows } = await pool.query(
'SELECT id, total FROM orders WHERE customer_id = $1 AND status = $2', [12, 'paid']);
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [100, 1]);
await client.query('COMMIT');
} catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); }[ { id: '10042', total: '249.50' }, { id: '10049', total: '199.00' } ]Go: pgx
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil { return err }
defer pool.Close()
rows, err := pool.Query(ctx,
"SELECT id, total FROM orders WHERE customer_id = $1 AND status = $2", 12, "paid")
if err != nil { return err }
defer rows.Close()
for rows.Next() {
var id int64; var total pgtype.Numeric
if err := rows.Scan(&id, &total); err != nil { return err }
}
return rows.Err()Java: JDBC with HikariCP
HikariConfig cfg = new HikariConfig();
cfg.setJdbcUrl("jdbc:postgresql://db.internal:5432/shop?sslmode=verify-full");
cfg.setUsername("app"); cfg.setPassword(System.getenv("DB_PASSWORD"));
cfg.setMaximumPoolSize(10);
try (var ds = new HikariDataSource(cfg);
var con = ds.getConnection();
var ps = con.prepareStatement("SELECT id, total FROM orders WHERE customer_id = ? AND status = ?")) {
ps.setLong(1, 12); ps.setString(2, "paid");
try (var rs = ps.executeQuery()) { while (rs.next()) { System.out.println(rs.getLong("id")); } }
}PHP: PDO with pdo_pgsql
$pdo = new PDO('pgsql:host=db.internal;dbname=shop;sslmode=verify-full', 'app', getenv('DB_PASSWORD'), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$stmt = $pdo->prepare('SELECT id, total FROM orders WHERE customer_id = :c AND status = :s');
$stmt->execute(['c' => 12, 's' => 'paid']);
$rows = $stmt->fetchAll();
$id = $pdo->query("SELECT nextval('orders_id_seq')")->fetchColumn();Pools, ORMs and Habits
Pool size: smaller than you think
A database with 8 cores cannot run more than about 8 queries truly at once; hundreds of connections just queue inside PostgreSQL with more context switching and memory. Keep application pools small, add PgBouncer in transaction mode when many services connect, and watch the ratio of active to total connections.
-- a starting point for the total across all application servers
connections ~= (CPU cores x 2) + number of disks
SELECT count(*) FILTER (WHERE state = 'active') AS active, count(*) AS total FROM pg_stat_activity; active | total
--------+-------
11 | 412
(1 row)What breaks behind PgBouncer in transaction mode
| Feature | Why it breaks | Workaround |
|---|---|---|
SET without LOCAL | the next transaction may run on another server connection | SET LOCAL inside the transaction, or ALTER ROLE ... SET |
| session advisory locks | lock stays on a connection another client gets | pg_advisory_xact_lock |
LISTEN | notifications arrive on a connection you no longer hold | a direct connection for listeners |
| temporary tables | they belong to one server session | ON COMMIT DROP inside one transaction |
| protocol level prepared statements | the statement lives on one server connection | PgBouncer 1.21+ max_prepared_statements |
See the SQL an ORM sends
ORMs produce the N+1 pattern by default: one query for a list, then one per item for a relation. Eager loading (select_related, prefetch_related, joinedload, include, with) turns that into one or two queries. pg_stat_statements with a huge call count for a simple WHERE id = $1 query is the usual symptom.
ALTER ROLE app SET log_min_duration_statement = 0; -- temporarily: log everything app runs
# Django: print(queryset.query), or django-debug-toolbar
# SQLAlchemy: create_engine(url, echo=True)
# Prisma: new PrismaClient({ log: ['query'] })
# Laravel: DB::enableQueryLog(); ... DB::getQueryLog();
ALTER ROLE app RESET log_min_duration_statement;Bulk inserts from code: COPY beats INSERT
COPY streams rows in one command with no per statement overhead, typically ten times faster than batched INSERTs and a hundred times faster than single row inserts in a loop. Load into a staging table first when you need ON CONFLICT handling, then INSERT ... SELECT from it.
# psycopg 3
with cur.copy("COPY events (user_id, kind, created_at) FROM STDIN") as copy:
for row in rows:
copy.write_row(row)
// node: pg-copy-streams; Go: pool.CopyFrom(ctx, pgx.Identifier{"events"}, cols, pgx.CopyFromRows(rows))Error Codes
SQLSTATE Codes Decoded
| SQLSTATE | Name | Message | Usual fix |
|---|---|---|---|
| 23505 | unique_violation | duplicate key value violates unique constraint | ON CONFLICT, or check the sequence with setval after a bulk load |
| 23503 | foreign_key_violation | insert or update on table violates foreign key constraint | insert the parent first, or delete children first |
| 23502 | not_null_violation | null value in column violates not-null constraint | provide the value or a DEFAULT |
| 23514 | check_violation | new row violates check constraint | fix the data, or the constraint |
| 22001 | string_data_right_truncation | value too long for type character varying(n) | widen the column or validate length |
| 22P02 | invalid_text_representation | invalid input syntax for type integer | cast or validate input; empty string is not NULL |
| 22003 | numeric_value_out_of_range | integer out of range | bigint, especially for ids |
| 22012 | division_by_zero | division by zero | x / nullif(y, 0) |
| 42P01 | undefined_table | relation "orders" does not exist | schema missing from search_path, or quoted mixed case name |
| 42703 | undefined_column | column "Name" does not exist | unquoted names fold to lower case |
| 42883 | undefined_function | function lower(integer) does not exist | add an explicit cast |
| 42601 | syntax_error | syntax error at or near | often a reserved word such as user or order used as a name |
| 42501 | insufficient_privilege | permission denied for table orders | GRANT, and ALTER DEFAULT PRIVILEGES for new tables |
| 42P07 | duplicate_table | relation already exists | IF NOT EXISTS |
| 2BP01 | dependent_objects_still_exist | cannot drop table because other objects depend on it | drop the dependents, or CASCADE with care |
| 25P02 | in_failed_sql_transaction | current transaction is aborted, commands ignored until end of transaction block | ROLLBACK, or use a savepoint |
| 40001 | serialization_failure | could not serialize access | retry the whole transaction |
| 40P01 | deadlock_detected | deadlock detected | retry; lock rows in a consistent order |
| 55P03 | lock_not_available | could not obtain lock / lock timeout | retry later; find the blocker |
| 57014 | query_canceled | canceling statement due to statement timeout | tune the query or the timeout |
| 53300 | too_many_connections | sorry, too many clients already | a pooler, smaller pools |
| 53100 | disk_full | could not extend file: No space left on device | free space; check WAL and replication slots |
| 28P01 | invalid_password | password authentication failed for user | the password, or md5 versus SCRAM |
| 3D000 | invalid_catalog_name | database "shop" does not exist | typo, or createdb |
| 08006 | connection_failure | server closed the connection unexpectedly | server logs: crash, OOM killer, or idle timeout |
Catch errors by SQLSTATE, not by message text
Message texts are translated with lc_messages and change between versions; SQLSTATE codes are stable and documented. Retry logic should key on 40001 and 40P01, and unique violations on 23505, never on string matching.
# psycopg 3
from psycopg import errors
try:
cur.execute("INSERT INTO tags (name) VALUES (%s)", ("oak",))
except errors.UniqueViolation:
conn.rollback()
# node-postgres: if (err.code === '23505') { ... }
# JDBC: if ("40001".equals(e.getSQLState())) { retry(); }Messages You Will See
Connection refused and pg_hba.conf rejects
Connection refused means nothing is listening at that address and port, so check the service, listen_addresses and firewalls. no pg_hba.conf entry means the server is reachable and refused the combination of address, user, database and SSL; the message tells you exactly which line to add.
sudo systemctl status postgresql # is it running?
SHOW listen_addresses; SHOW port; # is it listening beyond localhost?
-- add a pg_hba.conf line for 10.0.9.4, then SELECT pg_reload_conf();psql: error: connection to server at "db.internal" (10.0.3.17), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
psql: error: connection to server at "db.internal" (10.0.3.17), port 5432 failed: FATAL: no pg_hba.conf entry for host "10.0.9.4", user "app", database "shop", SSL encryptionMixed case names and relation does not exist
PostgreSQL folds unquoted identifiers to lower case, while quoted ones keep their exact case. Tools that generate DDL with quotes, as many ORMs and migration tools from other databases do, create names that must be quoted forever after. Lowercase snake_case avoids the whole problem.
CREATE TABLE "Customers" ("Name" text);
SELECT Name FROM Customers; -- fails: both fold to lower case
SELECT "Name" FROM "Customers"; -- works
ALTER TABLE "Customers" RENAME TO customers;ERROR: relation "customers" does not exist
LINE 1: SELECT Name FROM Customers;
^current transaction is aborted
After an error, PostgreSQL refuses every statement in the transaction until it ends, so a web request that swallowed the first error and continued sees this second one. Roll back, or wrap the risky statement in a SAVEPOINT; psql's ON_ERROR_ROLLBACK does this automatically for interactive use.
BEGIN;
SELECT 1/0;
SELECT 1; -- any statement now fails
ROLLBACK;ERROR: division by zero
ERROR: current transaction is aborted, commands ignored until end of transaction blockOut of memory and the OOM killer
When Linux runs out of memory it kills the biggest process, and PostgreSQL then restarts all sessions to protect shared memory. The usual causes are work_mem multiplied by many connections and complex queries, or too little RAM for shared_buffers plus connections. Set vm.overcommit_memory = 2 on dedicated database servers so allocations fail inside PostgreSQL instead.
sudo dmesg -T | grep -i -E 'killed process|out of memory'
grep -i 'terminated by signal 9' /var/log/postgresql/postgresql-18-main.log
SHOW work_mem; SHOW max_connections; SHOW shared_buffers;LOG: server process (PID 48213) was terminated by signal 9: Killed
LOG: terminating any other active server processes
LOG: all server processes terminated; reinitializingVersions & MySQL
Supported Releases
| Version | Released | Supported until | Latest minor, September 2026 |
|---|---|---|---|
| 19 | beta 4 on September 24, 2026; release candidate planned for early October, final release possibly in October | five years after release | beta |
| 18 | September 25, 2025 | November 14, 2030 | 18.6 |
| 17 | September 26, 2024 | November 8, 2029 | 17.11 |
| 16 | September 14, 2023 | November 9, 2028 | 16.15 |
| 15 | October 13, 2022 | November 11, 2027 | 15.19 |
| 14 | September 30, 2021 | November 12, 2026 | 14.24 |
| 13 | September 24, 2020 | ended November 13, 2025 | 13.23, final |
Which version am I on, and should I upgrade
Each major version gets five years of fixes. Minor releases, such as 18.5 to 18.6, contain only bug and security fixes and need just a restart with new binaries, so apply them promptly. Major upgrades change the data format and need pg_upgrade, a dump and restore, or logical replication. PostgreSQL 14 reaches end of life on November 12, 2026, so plan that upgrade now.
SELECT version();
SHOW server_version_num; -- 180006: easy to compare in scripts
psql --version server_version_num
--------------------
180006
(1 row)What Is New
PostgreSQL 18 highlights
SHOW io_method; -- asynchronous I/O
SELECT uuidv7(); -- time ordered UUIDs
ALTER TABLE t ADD COLUMN c int GENERATED ALWAYS AS (a + b); -- virtual by default
UPDATE t SET x = 1 RETURNING old.x, new.x; -- OLD and NEW in RETURNING
PRIMARY KEY (id, valid WITHOUT OVERLAPS) -- temporal keys
-- also: B-tree skip scan, statistics kept by pg_upgrade, EXPLAIN ANALYZE shows BUFFERS by default,
-- OAuth authentication, data checksums on by default, md5 passwords deprecated, casefold()PostgreSQL 19, as of beta 4
This list follows the 19 release notes and the beta 4 announcement of September 24, 2026. The release candidate is planned for early October and the final release could follow in October, but may slip; test against the release you deploy.
INSERT ... ON CONFLICT (k) DO SELECT RETURNING id; -- get or create in one statement
REPACK orders; -- replaces VACUUM FULL and CLUSTER
WAIT FOR LSN '0/3F2A1B8' WITH (TIMEOUT '2s'); -- read your own writes on a replica
SELECT lag(price) IGNORE NULLS OVER (ORDER BY day) FROM prices;
-- also: sequences replicated by logical replication, pg_plan_advice, parallel autovacuum,
-- jit off by default, a warning after every md5 login, RADIUS authentication removedAnnounced for 19, then reverted
Articles written in the spring still describe these as PostgreSQL 19 features. The community removed them late in the beta to keep the release reliable, so code or plans built on them need to wait for PostgreSQL 20.
-- committed during the 19 cycle and removed before release, likely to return in 20:
GROUP BY ALL -- reverted in July: wrong results with some ORDER BY cases
ALTER TABLE ... MERGE PARTITIONS / SPLIT PARTITION -- reverted in August: correctness problems
SQL/PGQ property graphs (GRAPH_TABLE) -- reverted on September 7
UPDATE / DELETE ... FOR PORTION OF -- reverted on September 15: concurrency problem
online enabling of data checksums -- reverted on September 16
pg_get_role_ddl() and related DDL functions -- removed in beta 4PostgreSQL Next to MySQL
The same task, translated
| Task | MySQL | PostgreSQL |
|---|---|---|
| auto increment key | id INT AUTO_INCREMENT PRIMARY KEY | id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY |
| quote an identifier | backticks around the name | "order" |
| upsert | ON DUPLICATE KEY UPDATE x = VALUES(x) | ON CONFLICT (k) DO UPDATE SET x = EXCLUDED.x |
| insert or skip | INSERT IGNORE | ON CONFLICT DO NOTHING |
| paging | LIMIT 20, 10 | LIMIT 10 OFFSET 20 |
| null fallback | IFNULL(a, b) | coalesce(a, b) |
| join strings in a group | GROUP_CONCAT(x SEPARATOR ',') | string_agg(x, ',') |
| format a date | DATE_FORMAT(d, '%Y-%m') | to_char(d, 'YYYY-MM') |
| boolean | TINYINT(1) | boolean |
| date and time | DATETIME | timestamp, or timestamptz for instants |
| case insensitive match | default collation | ILIKE, citext or a nondeterministic collation |
| last inserted id | LAST_INSERT_ID() | INSERT ... RETURNING id |
| show tables | SHOW TABLES | \dt |
| describe a table | DESCRIBE t | \d t |
| running queries | SHOW PROCESSLIST | SELECT * FROM pg_stat_activity |
| dump | mysqldump | pg_dump |
Behaviour that surprises people coming from MySQL
PostgreSQL is strict where MySQL is forgiving: no silent truncation, no zero dates, no implicit casts between text and numbers, case sensitive string comparison by default, and GROUP BY must name every non aggregated column unless it is functionally dependent on the key. Porting mostly means fixing queries that relied on MySQL guessing. The toolbox at the top converts much of the MySQL syntax for you.
SELECT 'abc' = 'ABC'; -- false: comparisons are case sensitive
SELECT '5' + 3; -- 8 only because '5' is an untyped literal
SELECT '5'::text + 3; -- error: no implicit text to number cast
SELECT count(*) FROM t WHERE flag = ''; -- '' is not NULL and not 0
BEGIN; CREATE TABLE x (id int); ROLLBACK; -- DDL rolls back tooERROR: operator does not exist: text + integer
LINE 1: SELECT '5'::text + 3;
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.One task, three databases
| PostgreSQL | MySQL | SQLite | |
|---|---|---|---|
| best at | complex queries, data integrity, extensions | simple web workloads, replication, managed hosting | embedded, single file, zero administration |
| concurrency | MVCC, row locks, many writers | MVCC in InnoDB, row locks | one writer at a time |
| JSON | jsonb with GIN indexes, jsonpath, JSON_TABLE | JSON type, multi valued indexes, JSON_TABLE | JSON functions on text |
| upsert | ON CONFLICT, MERGE | ON DUPLICATE KEY UPDATE | ON CONFLICT |
| transactional DDL | yes | no | yes |
| partial and expression indexes | yes | functional indexes, no partial | yes |
| license | PostgreSQL License, permissive | GPL plus commercial | public domain |
Removed and Renamed
recovery.conf is gone
Scripts and runbooks written before PostgreSQL 12 still create recovery.conf; a 12 or newer server refuses to start when it finds one, which is a nasty surprise during a restore.
recovery.conf -- recovery.signal or standby.signal, settings in postgresql.conf
standby_mode = on -- standby.signal
trigger_file -- pg_promote() or pg_ctl promoteRenamed in 13
wal_keep_segments = 64 -- wal_keep_size = '1GB'
pg_stat_statements.total_time -- total_exec_time, plus total_plan_time
pg_stat_statements.mean_time -- mean_exec_timeChanged in 15
pg_start_backup() / pg_stop_backup() -- pg_backup_start() / pg_backup_stop(); exclusive mode removed
CREATE on schema public for PUBLIC -- revoked by default in new databases; GRANT it explicitlyRemoved in 16 and 17
promote_trigger_file -- removed in 16: pg_promote()
vacuum_defer_cleanup_age -- removed in 16: hot_standby_feedback or a replication slot
old_snapshot_threshold -- removed in 17
db_user_namespace -- removed in 17
adminpack extension -- removed in 17
pg_stat_bgwriter.checkpoints_timed -- 17: pg_stat_checkpointer.num_timedNothing matches. Try a single word.
What Is a PostgreSQL Cheat Sheet
A PostgreSQL cheat sheet is a single page reference to the psql commands, SQL syntax and administration tasks of the PostgreSQL database, organised so a developer or administrator finds the right statement in seconds instead of searching the manual. People also call it a Postgres cheat sheet or a psql cheat sheet, and they usually mean the same mix of meta-commands, queries and maintenance commands.
This PostgreSQL cheat sheet covers 31 sections and 271 snippets for PostgreSQL 14 to 18, with a preview of 19. Every snippet that needs a newer release names the version that added it, and the server version picker next to the search box hides everything your server cannot run. Rows that need superuser or access to the server's files are marked self-hosted only, because they do not work on RDS, Cloud SQL, Azure and similar services. Each card holds copyable examples with a one line description, the output psql prints where it helps, and a short explanation of why PostgreSQL behaves that way.
The SQL toolbox at the top formats and lints queries, checks a migration for statements that take blocking locks, reads EXPLAIN ANALYZE plans in plain words and suggests indexes, converts MySQL DDL and queries to PostgreSQL, turns psql result tables into CSV or Markdown, builds IN and ANY lists and turns CSV or JSON into INSERT statements. The command builders write pg_dump and pg_restore commands, roles with the right GRANT and default privileges, connection strings in five formats, pg_hba.conf lines, a logical replication setup, a PgBouncer configuration and a starting postgresql.conf for your hardware. None of it sends anything to a server.
How It Differs From the Documentation
The PostgreSQL documentation is excellent and complete, and it is long. This page shows the shortest working form of the statements people actually run, next to the mistake that usually comes with them. For standard SQL that works across databases, see the SQL cheat sheet; for the MySQL way of doing the same things, the MySQL cheat sheet.
What This PostgreSQL Cheat Sheet Covers
The 31 sections follow the life of a database, from the first connection to running it in production, and each link jumps to that section above.
- Foundations: installing PostgreSQL and connecting with the toolbox and builders, psql meta-commands such as \d, \x and \copy, databases, schemas and search_path, PostgreSQL data types, and tables, constraints and safe ALTER TABLE.
- Querying: SELECT and filtering with DISTINCT ON and keyset pagination, joins and LATERAL, aggregates, FILTER and grouping sets, subqueries and CTEs, window functions, and built-in string, date and number functions.
- Changing data: INSERT, UPDATE, MERGE, upserts and COPY, JSON and JSONB, arrays and range types, transactions and locking, and full text search and trigrams.
- Performance: indexes from B-tree to BRIN, EXPLAIN and query tuning, VACUUM and autovacuum, server configuration, and partitioning.
- Logic: functions, procedures and PL/pgSQL, and views, materialized views and triggers.
- Administration: roles, privileges and row level security, backup and point in time recovery, streaming and logical replication, monitoring and upgrades, and extensions such as pgvector and PostGIS.
- Apps and help: PostgreSQL from Python, Node.js, Go, Java and PHP, SQLSTATE error codes with fixes, and versions and the differences from MySQL and SQLite.
PostgreSQL Commands List
The commands people look up most often, one line each. The sections above show each of them with options, output and the mistakes that come with them.
| Task | Command |
|---|---|
| Connect with psql | psql -h host -U user -d dbname |
| Show the server version | SELECT version(); |
| List databases | \l |
| Switch database | \c shop |
| Create a database | CREATE DATABASE shop OWNER app; |
| Delete a database | DROP DATABASE shop WITH (FORCE); |
| List schemas | \dn |
| List tables | \dt |
| Describe a table | \d orders |
| List roles | \du |
| Expanded output | \x auto |
| Time queries | \timing on |
| Run a SQL file | \i file.sql or psql -f file.sql |
| Import a CSV file | \copy t FROM 'file.csv' WITH (FORMAT csv, HEADER true) |
| Create a table | CREATE TABLE t (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text); |
| Add a column | ALTER TABLE t ADD COLUMN email text; |
| Rename a table | ALTER TABLE t RENAME TO customers; |
| Empty a table | TRUNCATE t RESTART IDENTITY; |
| Insert and get the id | INSERT INTO t (name) VALUES ('Ana') RETURNING id; |
| Insert or update | INSERT ... ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name; |
| Update rows | UPDATE t SET name = 'Ana M.' WHERE id = 1; |
| Delete rows | DELETE FROM t WHERE id = 1; |
| Latest row per group | SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC; |
| Read a JSON field | SELECT meta ->> 'tier' FROM customers; |
| Add an index without blocking writes | CREATE INDEX CONCURRENTLY ON orders (customer_id); |
| See a query plan | EXPLAIN (ANALYZE, BUFFERS) SELECT ...; |
| Clean up and refresh statistics | VACUUM (ANALYZE) orders; |
| Create a login role | CREATE ROLE app LOGIN PASSWORD '...'; |
| Grant table access | GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA public TO app; |
| Change a password | \password app |
| Back up a database | pg_dump -Fc -d shop -f shop.dump |
| Restore a backup | pg_restore -d shop -j 4 shop.dump |
| See running queries | SELECT pid, state, query FROM pg_stat_activity; |
| Stop a query | SELECT pg_cancel_backend(pid); |
| Read a setting | SHOW work_mem; |
| Change a setting permanently | ALTER SYSTEM SET work_mem = '32MB'; SELECT pg_reload_conf(); |
| Install an extension | CREATE EXTENSION pg_stat_statements; |
| Leave psql | \q |
psql Commands Cheat Sheet
psql is the command line client that ships with PostgreSQL. Its backslash meta-commands are handled by psql itself rather than the server, and these are the ones worth memorising.
| Meta-command | What it does |
|---|---|
\? | list every meta-command |
\h ALTER TABLE | SQL syntax help for a statement |
\conninfo | which database, user, host and port you are connected to |
\l | list databases |
\c dbname | connect to another database |
\dn | list schemas |
\dt, \dt schema.* | list tables |
\d name, \d+ name | describe a table, view, index or sequence |
\di, \dv, \dm, \ds | list indexes, views, materialized views, sequences |
\df, \sf name | list functions, show a function's source |
\du | list roles |
\dp name, \ddp | table privileges, default privileges |
\dx | installed extensions |
\x auto | expanded display for wide rows |
\timing on | show how long each statement took |
\pset null '(null)' | make NULL visible |
\e | edit the query buffer in $EDITOR |
\i file.sql, \ir | run a SQL file, relative to the current script |
\o file | send output to a file |
\copy | import or export a file on the client machine |
\set name value, :name | psql variables |
\gset, \gexec | store results in variables, run results as SQL |
\watch 2 | repeat the last query every 2 seconds |
\if, \elif, \else, \endif | conditionals in scripts |
\errverbose | the last error in full detail |
\bind | run a parameterized query, 16+ |
\password role | change a password without it reaching the logs |
\q | quit |
What PostgreSQL Is
PostgreSQL is an open source object-relational database management system: it stores data in tables, answers SQL, keeps data consistent with transactions and constraints, and lets you extend it with your own types, functions, index methods and whole extensions. It grew out of the POSTGRES project at the University of California, Berkeley, led by Michael Stonebraker from 1986; SQL support arrived in 1995 and the name PostgreSQL in 1996.
No company owns it. The PostgreSQL Global Development Group releases a new major version every autumn and supports each one for five years, and the code is under the permissive PostgreSQL License, which is why so many products, from Amazon Aurora and Google AlloyDB to Supabase, Neon and Timescale, are built on it. PostgreSQL 18 arrived on September 25, 2025, and PostgreSQL 19 is in beta, with a release candidate planned for early October 2026 and the final release possibly later that month.
Its reputation comes from strictness and depth: transactional DDL, real constraints including exclusion constraints, rich types such as jsonb, arrays and ranges, powerful indexing, and an extension system that gives it vector search, geospatial queries and time series features without leaving the database.
Where It Fits
PostgreSQL is the default choice for new applications that need a relational database, from small web apps to large SaaS platforms, and it handles mixed workloads well: transactional writes, reporting queries and JSON documents in one place. MySQL remains common where it is already established, SQLite is the answer when the database lives inside one application or device, a document database such as MongoDB fits records that vary in shape and are read as a whole, and a columnar warehouse still wins for analytics over billions of rows.
How PostgreSQL Runs a Query
Every statement passes through the same stages, and knowing them explains most of this cheat sheet.
- The client connects to the postmaster, which checks pg_hba.conf and authentication, then starts a dedicated backend process for that connection.
- The parser checks syntax and the analyzer resolves names through the search_path, which is where relation does not exist errors come from.
- The rewriter expands views and applies rules and row level security policies.
- The planner estimates the cost of possible plans using table statistics and picks the cheapest: which indexes, which join order, which join methods. EXPLAIN shows its choice.
- The executor runs the plan, reading pages through shared_buffers. Each row version carries the transaction ids that created and deleted it, and the executor shows each query only the versions visible to its snapshot. This is multiversion concurrency control, MVCC.
- Writes create new row versions and are recorded in the write ahead log, WAL, before the data files change. On COMMIT the WAL is flushed, which makes the change durable and feeds replication.
- Old row versions stay behind as dead tuples until VACUUM, usually autovacuum, makes their space reusable.
Most slow queries go wrong at step 4, when poor statistics or a missing index lead the planner to a plan that reads far more rows than the query returns, and most growing tables go wrong at step 7, when something prevents VACUUM from cleaning up. The EXPLAIN section and the VACUUM section cover both.
PostgreSQL, MySQL and SQLite Compared
The differences that matter when choosing, or when moving code from one to another.
| Question | PostgreSQL | MySQL | SQLite |
|---|---|---|---|
| Governance and license | community project, permissive PostgreSQL License | Oracle, GPL Community plus commercial Enterprise | public domain |
| Architecture | client server, one process per connection | client server, one thread per connection | a library inside the application |
| SQL strictness | strict types, no silent truncation | stricter since 5.7, still forgiving in places | flexible typing |
| Transactional DDL | yes | no | yes |
| JSON | jsonb, GIN indexes, jsonpath, JSON_TABLE | binary JSON, multi valued indexes | JSON functions over text |
| Extensibility | extensions: pgvector, PostGIS, TimescaleDB and many more | plugins and components | loadable extensions |
| Replication | streaming and logical replication | binary log, GTID, Group Replication | none built in |
Moving from MySQL is mostly mechanical: identity columns instead of AUTO_INCREMENT, double quotes instead of backticks, ON CONFLICT instead of ON DUPLICATE KEY UPDATE, and explicit casts where MySQL converted silently. The MySQL to PostgreSQL button in the toolbox handles most of the syntax, and the comparison section lists the rest.
Common PostgreSQL Mistakes
The same handful of problems shows up in almost every PostgreSQL database that has grown without a DBA.
In Schema and Queries
- Foreign keys without an index on the referencing column, so deletes and joins scan the child table.
- timestamp without time zone for instants, which breaks as soon as users or servers live in different zones.
- Mixed case identifiers created with quotes, which must then be quoted in every query forever.
- NOT IN with a subquery that can return NULL, which silently returns no rows.
- OFFSET pagination on large tables, where keyset pagination stays fast on every page.
- CREATE INDEX and ALTER TABLE on busy tables without CONCURRENTLY, NOT VALID or a lock_timeout.
In Operations
- Hundreds of direct connections instead of small pools and PgBouncer.
- Sessions left idle in transaction, which hold locks and stop VACUUM everywhere.
- Forgotten replication slots that keep WAL until the disk fills.
- Default autovacuum settings on tables with hundreds of millions of rows.
- Backups that were never restored, and pg_dump without the roles from pg_dumpall.
- No pg_stat_statements, so nobody knows which queries cost the most.
How to Learn PostgreSQL Well
Start With Queries, Then Plans
Get fluent with joins, aggregates, CTEs and window functions first, using psql with \timing and \x on a copy of real data. Then read EXPLAIN (ANALYZE, BUFFERS) for every query that matters until the node types feel familiar; paste plans into the toolbox above while you learn. If you work in Python, pair this with the Python cheat sheet; for JSON heavy data, the JSON cheat sheet covers the format itself.
Then Learn to Operate It
Understand MVCC and VACUUM, because they explain bloat, wraparound and most mysterious slowdowns. Practise a restore from pg_dump and a point in time recovery before you need them, and run PostgreSQL in a container with the Docker cheat sheet to experiment safely. After that, replication, partitioning and extensions build on the same ideas.
How This PostgreSQL Cheat Sheet Is Maintained
This page is written and maintained by Bogdan Sandu for TMS Outsource, a software development company. It was checked against the PostgreSQL 18 documentation, the release notes of versions 14 to 18 and the PostgreSQL 19 beta announcements on September 29, 2026. Features from 19 are marked as beta until the final release. If a snippet is wrong or out of date, the date in the byline shows when it was last reviewed.
PostgreSQL Questions People Actually Ask
The questions developers search for most about PostgreSQL and about this cheat sheet, answered in a few sentences each.
What is PostgreSQL used for?
PostgreSQL stores and serves the structured data of applications: accounts, orders, products, events and documents, queried with SQL. It runs web and mobile back ends, SaaS platforms, financial systems, geospatial applications with PostGIS and AI features with pgvector, and it is the engine behind many managed services such as Amazon RDS and Aurora, Google Cloud SQL and AlloyDB, Azure Database for PostgreSQL, Supabase and Neon.
Is Postgres the same as PostgreSQL?
Yes. Postgres is the original name of the Berkeley project and the common short form; PostgreSQL is the official name adopted in 1996 when SQL support was added. Both refer to the same database, and the documentation, community and tools use them interchangeably.
What is the difference between PostgreSQL and MySQL?
Both are open source relational databases. PostgreSQL is stricter about types and SQL standards, has transactional DDL, richer data types such as jsonb, arrays and ranges, more index types, and an extension system; MySQL is simpler to run for basic web workloads and has a long history in LAMP hosting. Syntax differs in places such as auto increment, identifier quoting, upserts and date functions.
How do I list databases and tables in PostgreSQL?
In psql, \l lists databases, \c name connects to one, \dt lists the tables in the search_path, \dt schema.* lists the tables of one schema and \d table describes a table. From SQL, query pg_database for databases and information_schema.tables or pg_catalog.pg_tables for tables.
Which PostgreSQL version should I use?
Use the newest major release your platform supports, which is PostgreSQL 18 as of September 2026, and keep up with its minor releases. PostgreSQL 14 reaches end of life on November 12, 2026, so plan to move off it. PostgreSQL 19 is in beta, with a release candidate planned for early October 2026; several announced features were reverted before release, so test it, but wait for the final release and its first minor update before production.
What is the difference between JSON and JSONB in PostgreSQL?
json stores the original text exactly, including whitespace, key order and duplicate keys, and re-parses it on every access. jsonb stores a parsed binary form that is slightly slower to write but much faster to query, supports containment operators and GIN indexes, and removes duplicate keys. Use jsonb unless you must preserve the exact input text.
How do I speed up a slow PostgreSQL query?
Run EXPLAIN (ANALYZE, BUFFERS) on it and look for sequential scans that discard most rows, row estimates far from the actual counts, and sorts or hashes that spill to disk. Usually the fix is an index that matches the WHERE clause and sort order, fresh statistics with ANALYZE, or a rewrite that avoids functions on indexed columns. Use pg_stat_statements to find the queries worth fixing first.
How do I back up and restore a PostgreSQL database?
For one database, pg_dump -Fc creates a compressed archive that pg_restore can load in parallel, and pg_dumpall --globals-only saves the roles, which pg_dump does not include. For large databases and point in time recovery, use physical backups with WAL archiving through a tool such as pgBackRest. Whatever you choose, restore a backup regularly to prove it works.
Is this PostgreSQL cheat sheet up to date?
Yes. It covers PostgreSQL 14 to 18 and previews 19, and was checked against the PostgreSQL 18 documentation and the 19 beta announcements on September 29, 2026. Every snippet that needs a newer release names the version that added it, the server picker hides what your version cannot run, 19 features are marked as beta and checked against the reverts made before release, and the date in the byline changes with every revision.
Can I download this PostgreSQL cheat sheet as a PDF?
Yes. The page has a print stylesheet, so your browser's print command with Save as PDF produces a clean copy: every output and explanation is included, and the search box, navigation and footer are left out. Run a search first to print only the snippets that are still visible.