Database / pgvector basics Interview Questions
How do you use EXPLAIN and EXPLAIN ANALYZE to debug pgvector queries?
EXPLAIN and EXPLAIN ANALYZE are essential for understanding whether pgvector queries are using indexes or falling back to slow sequential scans. Diagnosing this is often the first step in troubleshooting slow queries.
-- Basic EXPLAIN: shows the plan without running the query EXPLAIN SELECT id, content FROM documents ORDER BY embedding <=> '[0.1,0.2,0.3]' LIMIT 5; -- Sample output (with HNSW index): -- Limit (cost=...) -- -> Index Scan using documents_embedding_idx on documents -- Order By: (embedding <=> '[0.1,0.2,0.3]'::vector) -- This shows the index IS being used. -- Sample output (sequential scan - index not used): -- Limit (cost=...) -- -> Sort (cost=...) -- Sort Key: ((embedding <=> '[0.1,0.2,0.3]'::vector)) -- -> Seq Scan on documents -- This is slow - investigate why the index was not used! -- EXPLAIN ANALYZE: actually runs the query and shows real timings EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT id FROM documents WHERE category = 'tech' ORDER BY embedding <=> '[...]' LIMIT 5; -- Key metrics to look at in EXPLAIN ANALYZE: -- 'Seq Scan' vs 'Index Scan' - index should be used for KNN -- actual rows vs estimated rows - large discrepancy = stale stats -- actual time - how long each node actually took -- Buffers: hit=N miss=N - cache hit ratio -- Force sequential scan to compare: SET enable_indexscan = off; EXPLAIN ANALYZE SELECT id FROM documents ORDER BY embedding <=> '[...]' LIMIT 5; RESET enable_indexscan; -- Update statistics if planner makes poor decisions: ANALYZE documents; -- refresh table statistics
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...
