You want the customer-name search at Sunset Coffee to still find a name that has a typo. So you try SELECT similarity('Budi', 'Buddi'); in a brand-new PostgreSQL database (similarity() measures how alike two texts are). The answer isn't a number, it's an error: the function doesn't exist. The function does exist, it just isn't installed.
Features like similarity() come from an extension: a package of extra features for PostgreSQL, with new functions, data types, operators and indexes. You install an extension with one CREATE EXTENSION command. It works like apps on a phone. The phone stays the same, but once you install a dictionary app, the phone can translate words. Here, the phone is one database, and the app is the extension. Two rules work the same way too. The app must be in the app store (the extension's package must be on the server). And you install it on each phone separately (in each database).
Installing an extension
similarity() isn't a built-in PostgreSQL function. In a new database, PostgreSQL answers with this error:
ERROR: function similarity(unknown, unknown) does not exist
LINE 1: SELECT similarity('Budi', 'Buddi');
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
This error appears because the function belongs to the pg_trgm extension, which isn't installed yet. Once pg_trgm is installed, the same query answers 0.5714286.
These are the commands to install, list and remove an extension:
CREATE EXTENSION IF NOT EXISTS pg_trgm; -- install in this database
SELECT extname, extversion FROM pg_extension; -- what's installed (in psql: \dx)
SELECT name FROM pg_available_extensions; -- what this server can install
DROP EXTENSION pg_trgm; -- remove it again
CREATE EXTENSIONapplies to one database, the one you're using. Other databases on the same server don't have the feature yet.IF NOT EXISTSmakes the command safe to run again, for example in a migration.- An extension that doesn't come with PostgreSQL (such as PostGIS) must first be installed on the server's operating system.
pg_trgm: search that survives typos
pg_trgm splits text into trigrams: pieces of 3 letters in a row. The steps:
- Each word is changed to lowercase.
- The word gets 2 spaces in front and 1 behind.
- The result is cut into pieces of 3 letters, moving one letter each time.
| Text | Trigrams |
|---|---|
| Budi | " b", " bu", bud, udi, "di " |
| Buddi | " b", " bu", bud, udd, ddi, "di " |
4 trigrams are shared, and the two words together have 7 different trigrams. So similarity('Budi', 'Buddi') = 4 / 7 = 0.5714286.
The % operator is true when the similarity of two texts is above the pg_trgm.similarity_threshold limit, which is 0.3 by default. This % comes from pg_trgm: it is not the % sign in LIKE. This query finds the customers whose name is similar to 'Buddi', the closest first:
SELECT name, similarity(name, 'Buddi') AS sim
FROM customers
WHERE name % 'Buddi'
ORDER BY sim DESC;
-- Budi | 0.5714286 (Andi is only 0.1, Siti 0)
CREATE INDEX customers_name_trgm ON customers USING GIN (name gin_trgm_ops);
The last line makes a GIN index that stores the trigrams of each name (gin_trgm_ops). Both % and LIKE '%word%' can then use that index.
PostGIS: location data
PostGIS adds geospatial types and functions (data about places on earth): points, lines, areas, and distances on the earth's surface. Sunset Coffee looks for branches within 3 km of a customer at the Sydney Opera House:
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE TABLE branches (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
location geography(Point, 4326)
);
SELECT name, round(ST_Distance(location, ST_MakePoint(151.2153, -33.8568)::geography)) AS meter
FROM branches
WHERE ST_DWithin(location, ST_MakePoint(151.2153, -33.8568)::geography, 3000)
ORDER BY meter;
-- Sunset Coffee The Rocks | 677
-- Sunset Coffee Darlinghurst | 2390
geography(Point, 4326): a column type for a point on earth, in ordinary GPS coordinates (4326 is the code of the WGS 84 coordinate system).ST_MakePoint(longitude, latitude)makes a point: longitude first, then latitude. The Opera House sits at longitude 151.2 and latitude -33.9.::geographychanges that point into thegeographytype.ST_DWithin(a, b, 3000)is true when a and b are at most 3,000 metres apart, and it can use a GIST index.ST_Distancegives the distance in metres.
UUID and pgcrypto
Since PostgreSQL 13, gen_random_uuid() (which makes a UUID) is built in, with no extension. Before that, UUIDs came from the pgcrypto extension (which used to provide gen_random_uuid()) or uuid-ossp (uuid_generate_v4(), and other UUID versions). Old code and old migrations still often call uuid_generate_v4(), so you still see uuid-ossp a lot.
pgcrypto also provides cryptographic functions: hashing and encryption. Hashing turns a text into a code that can't be turned back into the original text. Encryption scrambles data so that it can only be read with a key. Below, digest() makes the SHA-256 hash of the voucher code SUNSET2026, and encode(..., 'hex') shows it as letters and digits.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
SELECT encode(digest('SUNSET2026', 'sha256'), 'hex');
-- daafca4b35634597d14be4e2fa9a3f449b068b97c93c5a85bbbc72eaf4afaab8
For user passwords, keep the hashing in the web app (Hash::make() in Laravel). That way the plain password is never sent inside a query, so it is never written to the database's log.
pg_stat_statements: which queries are slow
pg_stat_statements records statistics for every query: how many times it ran, and how long it takes on average. Unlike other extensions, it must be loaded when the server starts, through postgresql.conf (the server's settings file). The last query shows the three queries with the longest average time:
-- 1. in postgresql.conf, then restart the server:
-- shared_preload_libraries = 'pg_stat_statements'
-- 2. in the database:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT calls, round(mean_exec_time::numeric, 1) AS ms, query
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 3;
If you skip step 1 in the code's comments, the SELECT is refused: ERROR: pg_stat_statements must be loaded via "shared_preload_libraries".
Choosing an extension
| Need | Extension |
|---|---|
| fuzzy search, typo | pg_trgm |
| geolocation, maps | postgis |
| encryption, hash | pgcrypto |
| uuid | no extension needed since PostgreSQL 13 (gen_random_uuid()); uuid-ossp only appears in older code that calls uuid_generate_v4() |
| statistics | pg_stat_statements |
| search by meaning (embeddings, AI) | vector (pgvector) |
| anything else, such as a daily backup | unknown, not an extension's job |
The vector row in that table is the pgvector extension. pg_trgm finds text that is spelled alike, while pgvector finds text that means something alike. In a table that uses pgvector, each row stores an embedding: a list of numbers that stands for the meaning of a text, usually made by an AI model. The query below finds the two menu items closest in meaning to [0.9, 0.1, 0.2]:
CREATE EXTENSION IF NOT EXISTS vector; -- the name is vector, not pgvector
CREATE TABLE menu (id BIGINT PRIMARY KEY, name TEXT, embedding vector(3));
SELECT name, round((embedding <=> '[0.9, 0.1, 0.2]')::numeric, 3) AS distance
FROM menu
ORDER BY embedding <=> '[0.9, 0.1, 0.2]'
LIMIT 2;
-- Milk Coffee | 0.006
-- Palm Sugar Milk Coffee | 0.017
CREATE INDEX ON menu USING hnsw (embedding vector_cosine_ops);
<=>calculates the cosine distance: the smaller the distance, the closer the meaning. Themenutable holds Milk Coffee[0.9, 0.1, 0.1], Palm Sugar Milk Coffee[0.8, 0.2, 0.3], Milk Tea[0.1, 0.9, 0.1]and Toast[0.1, 0.1, 0.9]. Real embeddings hold hundreds to thousands of numbers.- An
hnswindex makes the search fast on millions of rows. Its results are approximate: they can differ a little from the results without the index. - Laravel 13:
Schema::ensureVectorExtensionExists()in a migration,$table->vector('embedding', 1536), thenorderByVectorDistance()orwhereVectorSimilarTo().
⚠️ Extensions that can't be found, points that land in the wrong place
- The package isn't on the server.
CREATE EXTENSION postgis;fails with a message that the extension's control file can't be found. Install the PostGIS package on the server's operating system first. On ready-made database services like Amazon RDS or Supabase, pick from the list of extensions they allow. - Forgetting that extensions are per database. The testing database needs
CREATE EXTENSIONtoo. Put the command in a migration. - Swapped coordinates.
ST_MakePoint(-33.8568, 151.2153)means latitude 151.2, a point that doesn't exist on earth. Longitude first, latitude second. - In the exercise, the text is exact.
"pg_trgm","postgis"(lowercase),"pgcrypto","pg_stat_statements","built-in"for UUIDs (no extension needed), and"unknown"for a need outside the list. Thevectorrow is not in the exercise.
TL;DR: Extensions are packages of extra features for PostgreSQL, installed per database with CREATE EXTENSION IF NOT EXISTS ...;. Until then their functions don't exist: similarity() (from pg_trgm) answers with an error. pg_trgm measures how alike texts are through trigrams, pieces of 3 letters in a row (Budi and Buddi are 0.5714286 alike), so search still works with typos. PostGIS adds location data: geography (a point on earth), ST_DWithin (search within a radius), ST_MakePoint(longitude, latitude). pgcrypto is for hashing and encryption (two ways to turn data into a scrambled code), uuid-ossp for uuid_generate_v4(), which makes UUIDs (since PostgreSQL 13, gen_random_uuid() is built in, with no extension). pg_stat_statements records slow queries, and must be loaded through shared_preload_libraries in postgresql.conf, and the server restarted.
⚡ A feature that isn't installed yet
Write:
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT similarity('Budi', 'Buddi');
Guess first: similarity() comes from the pg_trgm extension, which the first line installs. Without the first line, what does similarity() answer?
An error: the function doesn't exist. Once pg_trgm is installed, the answer is 0.5714286.
Meaning: An extension is a package of extra features for PostgreSQL: new functions, data types, operators and indexes. You install it per database with CREATE EXTENSION. similarity() measures how alike two texts are.
⚡ pg_trgm and PostGIS
Meaning: pg_trgm measures how alike texts are through trigrams, pieces of 3 letters in a row. Budi and Buddi are 0.5714286 alike (4 of 7 trigrams are shared), so a search for Buddi still finds Budi. PostGIS adds location data (points on earth and the distances between them). In ST_MakePoint, the function that makes a point, the longitude comes first, then the latitude.
⚡ UUID, pgcrypto, pg_stat_statements
Meaning: UUIDs (long ids that are practically never the same twice) used to come from the pgcrypto or uuid-ossp extension (uuid_generate_v4()). Since PostgreSQL 13, gen_random_uuid(), which makes UUIDs, is built in, with no extension. pgcrypto is also used for hashing and encryption (turning data into a code that can't simply be read). pg_stat_statements records how many times each query ran and how long it takes on average, so you can see the slow queries.
In the exercise, your function returns the name of the extension for a need, and the text must be exact: "pg_trgm", "postgis" (lowercase), "pgcrypto", "pg_stat_statements", "built-in" for UUIDs, and "unknown" for any other need.