Extensions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
An extension is a packaged set of SQL objects (types, functions, operators, index methods, views, sometimes a shared
library) installed with one command and versioned and removed as a unit. Extensions are how PostgreSQL grows without
changing the core: the same mechanism provides query statistics, fuzzy text search, vector similarity, geospatial types and
connections to other databases. This page uses PostgreSQL 18.6 (postgres:latest in container pg-b),
the pgvector/pgvector:pg18 image for vectors (pgvector 0.8.7) and a postgres:latest container with PostGIS 3.7.0
installed from the PostgreSQL apt repository (container pg-b2). The shop data is from
Getting Started. Large outputs are trimmed where stated.
Installing and listing extensions
An extension must first be present on the server’s disk (the contrib extensions ship with the official image; others come
from packages), then it is created per database. pg_available_extensions lists what can be installed, with the
default version and the installed one:
SELECT count(*) AS available FROM pg_available_extensions;
SELECT name, default_version, left(comment,60) AS comment FROM pg_available_extensions
WHERE name IN ('pg_stat_statements','pg_trgm','hstore','pageinspect','postgres_fdw','pgcrypto','uuid-ossp','citext','plpgsql')
ORDER BY name;
available
-----------
46
name | default_version | comment
--------------------+-----------------+--------------------------------------------------------------
citext | 1.8 | data type for case-insensitive character strings
hstore | 1.8 | data type for storing sets of (key, value) pairs
pageinspect | 1.13 | inspect the contents of database pages at a low level
pg_stat_statements | 1.12 | track planning and execution statistics of all SQL statement
pg_trgm | 1.6 | text similarity measurement and index searching based on tri
pgcrypto | 1.4 | cryptographic functions
plpgsql | 1.0 | PL/pgSQL procedural language
postgres_fdw | 1.2 | foreign-data wrapper for remote PostgreSQL servers
uuid-ossp | 1.1 | generate universally unique identifiers (UUIDs)
(The comment column is truncated to 60 characters.) A fresh database has only plpgsql. CREATE EXTENSION installs one and
\dx lists the installed ones:
CREATE EXTENSION pg_trgm;
\dx
List of installed extensions Name | Version | Default version | Schema | Description ---------+---------+-----------------+------------+------------------------------------------------------------------- pg_trgm | 1.6 | 1.6 | public | text similarity measurement and index searching based on trigrams plpgsql | 1.0 | 1.0 | pg_catalog | PL/pgSQL procedural language
Useful forms: CREATE EXTENSION IF NOT EXISTS x SCHEMA s, ALTER EXTENSION x UPDATE after installing a newer package,
and DROP EXTENSION x (add CASCADE to drop dependent columns and indexes). Creating most extensions needs superuser, or
membership of a role that is allowed for trusted extensions (a flag in the control file). Extensions that need to be
loaded at startup (pg_stat_statements, auto_explain, pg_cron) must be named in shared_preload_libraries before
the server starts.
A practical caution: extension objects live in a schema, so if you create one in public and your search_path omits it,
its types and functions seem missing (a type "vector" does not exist error is the classic symptom).
pg_stat_statements
The most useful extension for operating a database: it records normalised statement statistics. It requires
shared_preload_libraries = 'pg_stat_statements' and a restart; with the Docker image pass it on the command line:
docker run -d --name pg-b -e POSTGRES_PASSWORD=secret -p 54322:5432 postgres:latest \
-c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all
CREATE EXTENSION pg_stat_statements;
SELECT pg_stat_statements_reset();
-- run a workload: two count(*) queries with different constants, an aggregate and three primary-key lookups
SELECT calls, round(total_exec_time::numeric,1) AS total_ms, round(mean_exec_time::numeric,2) AS mean_ms,
rows, shared_blks_hit + shared_blks_read AS blks, left(query, 60) AS query
FROM pg_stat_statements WHERE query NOT LIKE '%pg_stat_statements%' ORDER BY total_exec_time DESC;
calls | total_ms | mean_ms | rows | blks | query
-------+----------+---------+------+-------+--------------------------------------------------------------
1 | 12.5 | 12.46 | 3 | 5713 | SELECT cust, sum(amount) FROM sales GROUP BY cust ORDER BY 2
2 | 12.1 | 6.05 | 2 | 11392 | SELECT count(*) FROM sales WHERE cust = $1
3 | 0.0 | 0.00 | 3 | 6 | SELECT * FROM orders WHERE id = $1
Literals are replaced by $1, so statements that differ only by constants share a row. Other columns include
total_plan_time (when pg_stat_statements.track_planning is on), temp_blks_written (spills), wal_bytes,
shared_blks_read and queryid, which also appears in EXPLAIN (VERBOSE) output. The tuning workflow built on this view is
in Performance Tuning. The related auto_explain module logs the plan of
statements slower than a threshold.
pg_trgm: fuzzy matching and LIKE indexes
A trigram is a three-character window. pg_trgm measures how many trigrams two strings share, giving typo-tolerant
matching and the ability to index LIKE '%text%', which a B-tree cannot serve.
SELECT similarity('Standing Desk', 'Standing Dsk'), 'Desk Lamp' % 'Desk Lmp' AS fuzzy, show_trgm('Lamp');
SELECT sku, name, round(similarity(name, 'ofice chair')::numeric,2) AS sim
FROM shop.products WHERE name % 'ofice chair' ORDER BY sim DESC;
similarity | fuzzy | show_trgm
------------+-------+-----------------------------
0.6875 | t | {" l"," la",amp,lam,"mp "}
sku | name | sim
-----+--------------+------
A-2 | Office Chair | 0.79
The % operator is true when similarity exceeds pg_trgm.similarity_threshold (0.3 by default), and <-> gives the
distance for nearest-match ordering. With a 200,000-row table of random hash strings, a substring search is a sequential scan:
Seq Scan on names (actual rows=11.00 loops=1) Filter: (name ~~ '%abc12%'::text) Rows Removed by Filter: 199989
After CREATE INDEX names_trgm ON shop.names USING gin (name gin_trgm_ops) the same query, and an ILIKE version, use the
index:
Bitmap Heap Scan on names (actual rows=11.00 loops=1)
Recheck Cond: (name ~~ '%abc12%'::text)
Rows Removed by Index Recheck: 2
Heap Blocks: exact=13
-> Bitmap Index Scan on names_trgm (actual rows=13.00 loops=1)
Index Cond: (name ~~ '%abc12%'::text)
The bitmap scan returned 13 candidate rows and rechecked them against the real predicate, discarding two. GiST with
gist_trgm_ops is the smaller alternative that also supports nearest-neighbour ordering. Patterns shorter than three
characters produce no useful trigrams, so they fall back to a scan. See
Indexing for GIN and GiST in general.
hstore, pageinspect and pgcrypto
hstore is a flat key-value type from before jsonb; new designs usually prefer jsonb
(see JSON & JSONB) but hstore is compact for string-only maps and converts easily:
CREATE EXTENSION hstore;
SELECT 'color=>oak, width=>160'::hstore -> 'color' AS color,
hstore('a','1') || hstore('b','2') AS merged,
hstore_to_jsonb('k=>v'::hstore) AS as_json;
color | merged | as_json
-------+--------------------+------------
oak | "a"=>"1", "b"=>"2" | {"k": "v"}
pageinspect (superuser only) reads raw pages and is useful for learning how storage works and for diagnosing corruption. It exposes the page header, the line pointers and tuple headers of a heap page, and B-tree metadata:
CREATE EXTENSION pageinspect;
SELECT lp, lp_off, lp_len, t_xmin, t_ctid FROM heap_page_items(get_raw_page('shop.customers', 0));
SELECT lower, upper, special, pagesize FROM page_header(get_raw_page('shop.customers', 0));
SELECT root, level, fastroot FROM bt_metap('shop.customers_pkey');
lp | lp_off | lp_len | t_xmin | t_ctid
----+--------+--------+--------+--------
1 | 8112 | 80 | 841 | (0,1)
2 | 8032 | 80 | 841 | (0,2)
3 | 7944 | 88 | 841 | (0,3)
4 | 7856 | 88 | 841 | (0,4)
lower | upper | special | pagesize
-------+-------+---------+----------
40 | 7856 | 8192 | 8192
root | level | fastroot
------+-------+----------
1 | 0 | 1
Tuples are stored from the end of the 8 kB page backwards (lp_off decreases) while the line-pointer array grows from the
front (lower = 40), and t_ctid is the tuple’s own position unless it has been updated. These are the structures
that vacuum and HOT updates operate on (see Architecture).
pgcrypto provides hashing, crypt() with bcrypt, and symmetric and PGP encryption. For example
crypt('secret', gen_salt('bf', 6)) produced a $2a$06$ bcrypt hash and digest('abc','sha256') returned
ba7816bf...15ad. Prefer hashing passwords in the application unless you have a reason not to, because the plain password
would otherwise pass through the SQL layer and logs.
Foreign data wrappers: postgres_fdw
A foreign data wrapper (FDW) lets SQL query an external data source as if it were a local table, following the SQL/MED
standard. postgres_fdw connects to another PostgreSQL server (here a second database warehouse on the same cluster,
holding a stock_levels table):
CREATE EXTENSION postgres_fdw;
CREATE SERVER warehouse FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', port '5432', dbname 'warehouse');
CREATE USER MAPPING FOR postgres SERVER warehouse OPTIONS (user 'postgres', password 'secret');
CREATE SCHEMA remote_wh;
IMPORT FOREIGN SCHEMA public LIMIT TO (stock_levels) FROM SERVER warehouse INTO remote_wh;
\det+ remote_wh.*
List of foreign tables Schema | Table | Server | FDW options | Description -----------+--------------+-----------+---------------------------------------------------+------------- remote_wh | stock_levels | warehouse | (schema_name 'public', table_name 'stock_levels') |
IMPORT FOREIGN SCHEMA created the column definitions from the remote table. The foreign table joins with local data:
SELECT p.sku, p.name, s.on_hand FROM shop.products p JOIN remote_wh.stock_levels s USING (sku)
WHERE s.on_hand < 20 ORDER BY sku;
sku | name | on_hand -----+---------------+--------- A-1 | Standing Desk | 12 B-7 | Desk Lamp | 15 C-9 | Monitor 27in | 7
EXPLAIN (VERBOSE) shows that the filter was pushed down to the remote server, so only matching rows cross the wire:
Hash Join
Hash Cond: (s.sku = p.sku)
-> Foreign Scan on remote_wh.stock_levels s
Remote SQL: SELECT sku, on_hand FROM public.stock_levels WHERE ((on_hand < 20))
-> Hash
-> Seq Scan on shop.products p
(Trimmed.) Pushdown of conditions, joins and aggregates is what makes FDWs usable; check the Remote SQL line when a federated
query is slow. Other wrappers exist for MySQL, MongoDB, files (file_fdw), Oracle and many more, and dblink is the older
ad hoc alternative. FDWs are a pragmatic integration or migration aid; they are not a substitute for replicating data you
query constantly (see Replication & High Availability).
pgvector: vector similarity search
pgvector adds a vector(n) type, distance operators and approximate nearest-neighbour indexes, so embeddings from a
language model can live next to the relational data they describe. The page ran pgvector/pgvector:pg18
(PostgreSQL 18.6, pgvector 0.8.7). For the retrieval-augmented generation context see
Vector Databases & RAG.
CREATE EXTENSION vector;
ALTER TABLE shop.products ADD COLUMN embedding vector(3);
UPDATE shop.products SET embedding = CASE sku
WHEN 'A-1' THEN '[0.9, 0.1, 0.0]' WHEN 'A-2' THEN '[0.8, 0.2, 0.1]'
WHEN 'B-7' THEN '[0.2, 0.9, 0.1]' WHEN 'C-3' THEN '[0.0, 0.3, 0.9]'
WHEN 'C-9' THEN '[0.1, 0.2, 0.95]' END::vector;
The three-dimensional vectors are hand-written for illustration (desks and chairs point one way, lighting another, electronics
a third). Real embeddings have hundreds or thousands of dimensions (vector(1536) is common) and come from an embedding
model; indexes support up to 2,000 dimensions.
SELECT sku, name, embedding FROM shop.products ORDER BY sku;
sku | name | embedding -----+---------------+---------------- A-1 | Standing Desk | [0.9,0.1,0] A-2 | Office Chair | [0.8,0.2,0.1] B-7 | Desk Lamp | [0.2,0.9,0.1] C-3 | USB-C Hub | [0,0.3,0.9] C-9 | Monitor 27in | [0.1,0.2,0.95]
Distance operators
| Operator | Distance | Typical use |
|---|---|---|
|
Euclidean (L2) |
General purpose |
|
Cosine distance (1 - cosine similarity) |
Text embeddings |
|
Negative inner product |
Normalised vectors; multiply by -1 to get the similarity |
|
Taxicab (L1) |
Sparse or count-like data |
Finding the products nearest to a query vector close to "desk-like", using all three main operators:
SELECT sku, name,
embedding <-> '[0.85,0.15,0.05]' AS l2,
embedding <=> '[0.85,0.15,0.05]' AS cosine,
(embedding <#> '[0.85,0.15,0.05]') * -1 AS inner_product
FROM shop.products ORDER BY embedding <-> '[0.85,0.15,0.05]' LIMIT 3;
sku | name | l2 | cosine | inner_product -----+---------------+---------------------+-----------------------+-------------------- A-1 | Standing Desk | 0.08660251521411114 | 0.0037184699510960373 | 0.7799999713897705 A-2 | Office Chair | 0.08660254478757834 | 0.004420605342517536 | 0.7150000333786011 B-7 | Desk Lamp | 0.9937303517156598 | 0.6133599094870286 | 0.3100000023841858
The lamp is much farther away than the two furniture items, as intended. Functions such as l2_distance(a, b),
cosine_distance, vector_dims and l2_norm are also available (they need explicit ::vector casts on literals), and
avg(embedding) computes a centroid:
avg ------------------ [0.85,0.15,0.05]
(the average embedding of the two furniture products.) Combining similarity with ordinary filters is the strength of keeping vectors in PostgreSQL:
SELECT sku, name, round((embedding <=> '[0.1,0.3,0.9]')::numeric,4) AS dist
FROM shop.products WHERE category = 'electronics' ORDER BY embedding <=> '[0.1,0.3,0.9]' LIMIT 2;
sku | name | dist -----+--------------+-------- C-3 | USB-C Hub | 0.0055 C-9 | Monitor 27in | 0.0065
HNSW and IVFFlat indexes
Without an index, a nearest-neighbour query computes the distance to every row and keeps the best few: exact, but it
scales linearly. A table docs of 50,000 random 64-dimensional vectors (15 MB) shows the difference. The query vector
below is one of the stored vectors and is shown abbreviated as [0.5489,0.361,...]:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY ON, BUFFERS OFF)
SELECT id FROM docs ORDER BY embedding <=> '[0.5489,0.361,...]' LIMIT 5;
Limit (actual rows=5.00 loops=1)
-> Sort (actual rows=5.00 loops=1)
Sort Key: ((embedding <=> '[0.5489,0.361,...]'::vector))
Sort Method: top-N heapsort Memory: 25kB
-> Seq Scan on docs (actual rows=50000.00 loops=1)
Execution Time: 4.138 ms
HNSW (Hierarchical Navigable Small World) builds a multi-layer proximity graph: it has the best speed-recall trade-off, costs more to build and store, and needs no training data.
CREATE INDEX docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);
hnsw_size
-----------
27 MB
Limit (actual rows=5.00 loops=1)
-> Index Scan using docs_hnsw on docs (actual rows=5.00 loops=1)
Order By: (embedding <=> '[0.5489,0.361,...]'::vector)
Execution Time: 0.577 ms
The index is 27 MB, larger than the 15 MB table, and the query dropped from 4.1 ms to 0.6 ms. The query-time knob is
hnsw.ef_search (default 40): larger values examine more candidates for better recall at a cost in speed. Recall can be
measured by comparing the ten nearest neighbours returned with the index against the exact result computed without it
(saved to a temporary table beforehand). Here HNSW returned all 10 of the true top 10 at the default ef_search, and also at 200.
IVFFlat partitions the vectors into lists clusters using k-means and searches only the nearest probes clusters. It
builds faster and is smaller, but must be created after the table has data (the clusters are trained on it), and its recall
depends on probes:
CREATE INDEX docs_ivf ON docs USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
ivf_size ---------- 14 MB Limit (actual rows=5.00 loops=1) -> Index Scan using docs_ivf on docs (actual rows=5.00 loops=1) Execution Time: 0.065 ms
At the default ivfflat.probes = 1 the query takes 0.065 ms, but only 3 of the true top 10 were found; with
SET ivfflat.probes = 20 it found 8. This table holds uniformly random vectors, which have no cluster structure, so it is a
pessimistic case for IVFFlat; real embeddings cluster much better, but the lesson is general: measure recall on your own data
and choose probes, ef_search, m and lists from that measurement.
| Aspect | HNSW | IVFFlat |
|---|---|---|
Build |
Slower, more memory |
Faster |
Index size |
Larger (27 MB here) |
Smaller (14 MB here) |
Recall/speed |
Better trade-off, tune |
Tune |
Training |
None; can be created on an empty table |
Required; rebuild if the data distribution shifts |
Index the column on a real table the same way (CREATE INDEX products_emb_hnsw ON shop.products USING hnsw (embedding vector_l2_ops) succeeded on the five-row table; an index is pointless at that size). Use the operator class matching the
operator in your query (vector_l2_ops for <->, vector_cosine_ops for <=>, vector_ip_ops for <#>), or the index
is ignored. Filtered queries combine an approximate index scan with a WHERE: when the filter is highly selective, the index may return too few matching rows,
so consider partial indexes, partitioning, or raising hnsw.ef_search (pgvector 0.8 added iterative scans to
mitigate this).
PostGIS: geospatial data
PostGIS adds geometry and geography types, hundreds of spatial functions and GiST/SP-GiST index support. There is no official
arm64 PostGIS image, so on this Apple Silicon host the example installs it from the PostgreSQL apt repository inside a
stock postgres:latest container:
docker exec pg-b2 sh -c "apt-get update -qq && apt-get install -y -qq postgresql-18-postgis-3"
pg_available_extensions then lists postgis, postgis_raster, postgis_topology and postgis_sfcgal, all at 3.7.0:
CREATE EXTENSION postgis;
SELECT postgis_version();
postgis_version --------------------------------------- 3.7 USE_GEOS=1 USE_PROJ=1 USE_STATS=1
geometry works on a flat plane with coordinates in a spatial reference system (SRID); geography works on the earth’s spheroid, with distances in metres. Add a location to the customers (coordinates are longitude, latitude, SRID 4326):
ALTER TABLE shop.customers ADD COLUMN location geography(Point, 4326);
UPDATE shop.customers SET location = ST_SetSRID(ST_MakePoint(lon, lat), 4326)::geography
FROM (VALUES ('c-1', -0.1276, 51.5072), ('c-2', -2.2278, 53.3244),
('c-3', -74.0060, 40.7128), ('c-4', 24.9384, 60.1699)) AS v(id, lon, lat)
WHERE customers.id = v.id;
SELECT id, city, ST_AsText(location) AS wkt FROM shop.customers ORDER BY id;
id | city | wkt -----+----------+------------------------ c-1 | London | POINT(-0.1276 51.5072) c-2 | Wilmslow | POINT(-2.2278 53.3244) c-3 | New York | POINT(-74.006 40.7128) c-4 | Helsinki | POINT(24.9384 60.1699)
Distances come back in metres (divided here to kilometres), and ST_DWithin answers "within this radius":
SELECT a.city AS a, b.city AS b, round((ST_Distance(a.location, b.location)/1000)::numeric) AS km
FROM shop.customers a JOIN shop.customers b ON a.id < b.id WHERE a.id='c-1' ORDER BY km;
SELECT city FROM shop.customers
WHERE ST_DWithin(location, ST_SetSRID(ST_MakePoint(-0.1276, 51.5072),4326)::geography, 300000) ORDER BY city;
a | b | km --------+----------+------ London | Wilmslow | 248 London | Helsinki | 1826 London | New York | 5585 city ---------- London Wilmslow
Planar geometry functions need no earth model: ST_Buffer, ST_Area(ST_MakeEnvelope(0,0,2,3)) (6) and
ST_Intersects(...) work on plain coordinates.
GiST index for spatial queries
A 200,000-point table places scattered over Europe shows the index effect for a 50 km radius search around Paris. Without
an index, the planner scans the whole table:
Finalize Aggregate (actual rows=1.00 loops=1)
-> Gather (actual rows=2.00 loops=1)
-> Partial Aggregate (actual rows=1.00 loops=2)
-> Parallel Seq Scan on places (actual rows=235.50 loops=2)
Filter: st_dwithin(geog, '0101000020E6...'::geography, '50000'::double precision, true)
Rows Removed by Filter: 99764
After CREATE INDEX places_gix ON places USING gist (geog), ST_DWithin is rewritten into an index-friendly bounding-box
test and an exact re-check:
Aggregate (actual rows=1.00 loops=1)
-> Bitmap Heap Scan on places (actual rows=471.00 loops=1)
Filter: st_dwithin(geog, '0101000020E6...'::geography, '50000'::double precision, true)
Rows Removed by Filter: 341
Heap Blocks: exact=651
-> Bitmap Index Scan on places_gix (actual rows=812.00 loops=1)
Index Cond: (geog && _st_expand('0101000020E6...'::geography, '50000'::double precision))
The index returned 812 candidates inside the expanded bounding box; the exact distance filter kept 471. K-nearest-neighbour
queries use the distance operator in ORDER BY, which the GiST index also serves:
SELECT id, round((ST_Distance(geog, ST_SetSRID(ST_MakePoint(2.35,48.85),4326)::geography)/1000)::numeric,1) AS km
FROM places ORDER BY geog <-> ST_SetSRID(ST_MakePoint(2.35,48.85),4326)::geography LIMIT 3;
id | km --------+----- 120999 | 1.7 178220 | 4.4 178603 | 4.8
(The coordinates are random, so ids will differ on another run.)
Other extensions to know
Mentioned for orientation and not run here:
-
TimescaleDB turns tables into time-partitioned hypertables with compression and continuous aggregates, for time-series workloads.
-
Citus distributes tables across nodes (sharding) for scale-out analytics and multi-tenant applications.
-
pg_cron schedules SQL inside the server; pg_partman automates partition creation; pg_repack rebuilds bloated tables online; pgaudit adds audit logging; btree_gin/btree_gist allow scalar types in GIN and GiST indexes; citext provides a case-insensitive text type; uuid-ossp and the built-in
gen_random_uuid()generate identifiers.
Treat extensions as part of your deployment: pin versions, list them in migrations, test upgrades (ALTER EXTENSION ... UPDATE)
and remember that managed services allow only a vetted subset. See
Choosing the Right Database for when a dedicated vector or geospatial store is
the better fit.