Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 25/ 160
02. RAG

pgvector

Postgres extension for embeddings when you want SQL + vectors in one operational store.

IntermediatePostgres · IVFFlat/HNSW3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

It lets your normal database store the number-lists for text and quickly find the closest ones, using the same SQL you already know.

Think of it like…

Adding a new kind of index card (a similarity lookup) to a filing cabinet you already own and trust, instead of building a second cabinet and keeping the two in sync by hand.

Where you’ve seen it

A support platform stores 3 million help-article chunks in chunks(id, tenant_id, content, embedding vector(1024)). Retrieval is SELECT id, content FROM chunks WHERE tenant_id = $1 ORDER BY embedding <=> $2 LIMIT 8; with an HNSW index on embedding vector_cosine_ops and a B-tree on tenant_id. When a customer edits an article, the row and its new embedding are updated in one transaction, so search never serves stale or half-updated content.

Words you’ll hear

vector(n)
Column type for n-dimensional float vectors (n up to 16,000 stored; indexes support up to 2,000).
HNSW
Hierarchical graph index; tune m, ef_construction at build and hnsw.ef_search at query time.
IVFFlat
Cluster-based index; tune lists at build and ivfflat.probes at query time.
Iterative scan
pgvector 0.8+ option that keeps scanning the index to fill LIMIT results when filters discard candidates.

Visual diagram

Loading interactive diagram

Theory & deep dive

Setting up tables, indexes and queries

CREATE EXTENSION vector; then ALTER TABLE chunks ADD COLUMN embedding vector(1024);. Insert vectors as arrays ('[0.1, 0.2, ...]') or through a client library. Create an HNSW index matching your metric: CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);. At query time SET hnsw.ef_search = 100; trades latency for recall (default 40). IVFFlat is built with USING ivfflat (embedding vector_cosine_ops) WITH (lists = 1000) after loading data, and queried with SET ivfflat.probes = 10; a common start is lists ≈ rows/1,000 for up to a million rows and √rows beyond.

Without an index, ORDER BY embedding <=> $1 LIMIT k does an exact scan: perfect recall, slow at scale. The query's ORDER BY expression must use the same operator as the index (cosine with vector_cosine_ops), or the planner ignores the index. Build indexes with maintenance_work_mem raised and after bulk loading, and use CREATE INDEX CONCURRENTLY on live tables. Smaller types help: halfvec (16-bit floats) halves memory and supports higher dimensions in indexes, and bit with Hamming distance supports binary-quantised vectors.

A complete setup

CREATE INDEX CONCURRENTLY chunks_emb_hnsw ON chunks USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64); then SET hnsw.ef_search = 100; SELECT id FROM chunks WHERE tenant_id = 42 ORDER BY embedding <=> $1 LIMIT 8;

Key takeaway: Match operator class to operator; tune ef_search or probes for recall.

Filtering, scale and when to move on

An ANN index returns the nearest rows first, and a WHERE clause is applied to them afterwards, so a selective filter can return fewer than LIMIT rows. Mitigations: raise ef_search, enable iterative index scans (SET hnsw.iterative_scan = relaxed_order in pgvector 0.8+), add a B-tree or partial index so the planner uses the filter first for very selective predicates, or partition by tenant so each partition has its own small index. Always measure recall with your real filters against an exact scan.

Operational limits: HNSW build time and memory grow with data (tens of millions of vectors take hours and large RAM), indexes should fit in memory for stable latency, and updates add graph maintenance cost. pgvector comfortably serves up to a few million vectors per instance with good tuning, and more with read replicas, partitioning and halfvec. Move to a dedicated vector store when you need many tens of millions of vectors with strict latency, heavy filtered search across many tenants, or independent scaling of search from the transactional workload.

Checking recall against exact search

Run 200 queries twice: once with SET enable_indexscan = off (exact) and once with the index. Recall@10 = overlap of result ids ÷ 10 per query, averaged. Raise ef_search until recall reaches your target (for example 0.95).

Key takeaway: Filters need care; measure recall; scale-up limits tell you when to move.

How it works, step by step

Step 1 of 4
Schema

1. Create the column and load data

Add the extension and a vector(n) column matching the embedding model's dimensions, then bulk-load vectors.

embedding vector(1024)
Key numbers at this step
Dims
must match the model

When to use it & trade-offs

What it is

pgvector is a PostgreSQL extension that adds a vector(n) column type, distance operators and approximate indexes, so embeddings live beside ordinary relational data. Operators: <-> (L2 distance), <=> (cosine distance), <#> (negative inner product). Two index types: HNSW (graph, better recall and speed, slower to build, more memory) and IVFFlat (clustered lists, faster to build, needs data first and tuning of lists and probes). You get SQL filters, joins, transactions and backups in the same database.

Why it matters: For many teams the best vector database is the PostgreSQL they already run: no second system to sync, filters are plain WHERE clauses, embeddings update in the same transaction as the source row, and permissions use existing roles. Knowing pgvector's limits and tuning knobs lets you decide confidently when it's enough and when to move to a dedicated store.

When to reach for it

  • RAG where content already lives in PostgreSQL
  • Transactional updates of text and embeddings together
  • Semantic search with SQL joins and filters

When to avoid or be careful

  • ORDER BY with a different operator than the index
  • Building IVFFlat on an empty table
  • Trusting recall without testing with filters

pgvector index types

HNSW
Best for: Most workloads needing high recall and low latency

Strengths: Better speed-recall trade-off; no training step; handles updates.

Watch out: Slower builds; more memory.

IVFFlat
Best for: Faster builds and smaller indexes on static-ish data

Strengths: Quick to build; lower memory.

Watch out: Needs data before indexing; recall depends on lists and probes.

No index (exact scan)
Best for: Small tables or maximum recall

Strengths: Perfect recall; simplest.

Watch out: Latency grows linearly with rows.

Interview signals & numbers to know

When this topic comes up

  • “Can we just use Postgres for vectors?”
  • “The vector index isn't used”
  • “Filtered vector queries return too few rows”
  • HNSW vs IVFFlat
  • Embeddings in transactional systems

Benchmarks & rules of thumb

40 -
default hnsw.ef_search
16 / 64 -
default HNSW m / ef_construction
2,000 -
max dimensions for vector indexes

Common mistakes & follow-ups

Common interview mistakes

  • Creating the index with vector_l2_ops and querying with <=>, so every query scans the table.
  • Creating an IVFFlat index before loading data, producing poor clusters and low recall.
  • Raising LIMIT to compensate for a selective filter instead of fixing the filtered search.

Likely interviewer follow-ups

  • HNSW or IVFFlat: how do you choose?
  • How do you make filtered vector search return enough results?
  • When would you move off pgvector?
Interview tip: Mention the operator-class match and measuring recall with filters against exact search. Those are the two details that separate working pgvector setups from broken ones.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply pgvector with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Vector Databases
Next topic
HNSW Indexes