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;
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
