Database / pgvector basics Interview Questions
How do you perform vector arithmetic and other vector functions in pgvector?
pgvector exposes several SQL functions and operators for vector arithmetic - useful for computing centroids, adding noise, normalising vectors, or combining them mathematically before storage or search.
-- Vector arithmetic operators: -- + : element-wise addition -- - : element-wise subtraction -- * : element-wise multiplication SELECT '[1,2,3]'::vector + '[4,5,6]'::vector; -- [5,7,9] SELECT '[4,5,6]'::vector - '[1,2,3]'::vector; -- [3,3,3] SELECT '[1,2,3]'::vector * '[2,2,2]'::vector; -- [2,4,6] -- Compute the L2 norm (magnitude) of a vector: SELECT l2_norm('[1,2,2]'::vector); -- sqrt(1+4+4) = 3.0 -- Normalise a vector (make unit length): SELECT l2_normalize('[1,2,2]'::vector); -- Result: [0.333, 0.667, 0.667] (each / 3.0) -- Compute the average (centroid) of multiple vectors: SELECT avg(embedding) FROM documents WHERE category = 'technical'; -- Returns the centroid vector of all 'technical' embeddings -- Useful for finding the 'centre' of a cluster -- Compute the sum of all vectors: SELECT sum(embedding) FROM documents; -- Round-trip: store normalised version of an embedding UPDATE documents SET embedding = l2_normalize(embedding) WHERE id = 1; -- Convert between types: SELECT embedding::halfvec(1536) FROM documents WHERE id = 1; SELECT embedding::vector(1536) FROM documents WHERE id = 1;
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...
