Database / pgvector basics Interview Questions
What is the difference between exact and approximate nearest-neighbour search in pgvector?
pgvector supports two search modes with very different performance and accuracy characteristics. Choosing the right one depends on dataset size and whether you need perfect recall.
| Aspect | Exact (sequential scan) | Approximate (ANN with index) |
|---|---|---|
| Method | Computes distance to EVERY row | Searches a smart subset of rows |
| Recall | 100% - always finds the true nearest neighbours | Less than 100% - may miss some true neighbours |
| Speed at scale | Slow O(n) per query | Sub-linear; fast even at millions of rows |
| Configuration | No index needed | Requires HNSW or IVFFlat index |
| Good for | < ~100k rows or when 100% recall needed | Millions of rows; speed more important than perfect recall |
| Index required | No | Yes (HNSW or IVFFlat) |
-- EXACT search (no index): scans every row -- Accurate but slow at scale SELECT id, embedding <-> '[3,1,2]' AS dist FROM items ORDER BY dist LIMIT 5; -- APPROXIMATE search (with HNSW index): fast, high recall -- Create the index: CREATE INDEX ON items USING hnsw (embedding vector_l2_ops); -- Same query syntax - PostgreSQL uses the index automatically: SELECT id, embedding <-> '[3,1,2]' AS dist FROM items ORDER BY dist LIMIT 5; -- Now uses HNSW index for fast approximate search -- Check which index was used: EXPLAIN SELECT id FROM items ORDER BY embedding <-> '[1,2,3]' LIMIT 5; -- Look for 'Index Scan using items_embedding_idx' in the plan -- Force exact search even when index exists: SET enable_indexscan = off; SELECT id FROM items ORDER BY embedding <-> '[1,2,3]' LIMIT 5; RESET enable_indexscan;
More Related questions...