Technical Guides

A practical guide to vector search in PostgreSQL with pgvector

Learn how pgvector stores embeddings, run a nearest-neighbor query, and decide when an approximate index is useful.

SQL & DatabasesAI & LLMs

You can add vector similarity search to PostgreSQL with the open-source pgvector extension. It lets an application keep relational records and their embeddings in the same database, then rank records by distance. Start with exact search; add an approximate index only after you have measured a real query bottleneck.

This guide uses a three-dimensional vector so the SQL stays readable. Real embedding models usually produce vectors with many more dimensions. Treat the values here as synthetic demonstration data.

1. Enable the extension

Install pgvector using the instructions for your PostgreSQL platform, then enable it in the database where you need vector columns:

CREATE EXTENSION IF NOT EXISTS vector;

The extension adds a vector data type and distance operators. It does not generate embeddings for you; an application or embedding service must create those values.

2. Store vectors with the records they describe

Here is a tiny document table. The three dimensions make the sample vectors easy to inspect:

CREATE TABLE knowledge_chunks (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  body text NOT NULL,
  embedding vector(3) NOT NULL
);

INSERT INTO knowledge_chunks (body, embedding) VALUES
  ('Backups should be tested by restoring them.', '[0.10, 0.80, 0.20]'),
  ('An index can reduce the work required by a query.', '[0.70, 0.15, 0.35]'),
  ('A restore drill verifies a backup workflow.', '[0.12, 0.77, 0.21]');

Keep a reference to the source record and any metadata your application needs, such as tenant, document, or access scope. A similarity score by itself is not an authorization check.

3. Run an exact nearest-neighbor query

The <-> operator orders results by Euclidean distance. This query compares every stored vector with a sample query vector and returns the nearest rows:

SELECT id, body, embedding <-> '[0.11, 0.79, 0.19]' AS distance
FROM knowledge_chunks
ORDER BY embedding <-> '[0.11, 0.79, 0.19]'
LIMIT 2;

The first result should be one of the two backup-related chunks. For cosine distance, pgvector provides the <=> operator; inner product is available through <#>. Use the operator and index operator class that match the metric used by your embedding model and retrieval design.

4. Add an approximate index only when it helps

Exact search is simple and returns the true nearest neighbors, but it compares the query vector against the candidate rows. If a measured workload makes that too slow, pgvector supports approximate indexes including HNSW and IVFFlat. For example:

CREATE INDEX knowledge_chunks_embedding_hnsw
ON knowledge_chunks USING hnsw (embedding vector_l2_ops);

An approximate index trades some recall for lower search work. The best choice depends on table size, latency needs, recall targets, memory, and the distance metric. Benchmark using representative queries and data; an index is not automatically faster for every small table or workload.

5. Check what PostgreSQL is doing

Use EXPLAIN (ANALYZE, BUFFERS) with a representative query to inspect the chosen plan and actual execution time. Compare results against exact search on a sample so you can see how much recall the approximate index gives up. PostgreSQL’s query planning documentation explains how to read the plan.

For production retrieval, also measure end-to-end quality: the nearest chunk may still be irrelevant, incomplete, or outside the user’s permissions. Filtering, text search, reranking, and access controls remain application design decisions.

When this approach fits

Keeping vectors in PostgreSQL is worth exploring when your product already uses PostgreSQL and wants a compact path to semantic retrieval beside ordinary records. A separate vector service may fit better when scale, isolation, specialized filtering, or independent operations justify another system. Prototype with your real data shape and evaluate before committing either way.

Sources