Database / pgvector basics Interview Questions
How does pgvector handle NULL values in vector columns?
pgvector follows standard PostgreSQL NULL semantics. Vector columns can contain NULL values, and NULL vectors are excluded from distance calculations and index scans. This is useful for records where an embedding has not yet been generated.
-- Create table allowing NULLs (default behaviour) CREATE TABLE documents ( id BIGSERIAL PRIMARY KEY, content TEXT, embedding VECTOR(1536) -- nullable by default ); -- Insert without embedding (embedding is NULL) INSERT INTO documents (content) VALUES ('Article not yet embedded'); -- NULL rows are automatically excluded from similarity queries -- (they cannot have a meaningful distance) SELECT id, content FROM documents ORDER BY embedding <-> '[0.1,0.2,...]' -- NULLs won't appear in results LIMIT 5; -- Find rows missing embeddings (need to be processed): SELECT id, content FROM documents WHERE embedding IS NULL; -- Count unembedded documents: SELECT COUNT(*) FROM documents WHERE embedding IS NULL; -- Prevent NULLs if all rows must have embeddings: CREATE TABLE documents_required ( id BIGSERIAL PRIMARY KEY, content TEXT, embedding VECTOR(1536) NOT NULL -- enforce non-null ); -- Partial index to cover only non-NULL rows -- (useful for variable-dimension or partially-embedded tables): CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops) WHERE embedding IS NOT NULL;
More Related questions...