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;
More Related questions...