Sub topic 5
Inserting and updating vectors
This chapter assumes you can write basic INSERT and UPDATE statements. It also assumes you have enabled pgvector and created the items table from the earlier chapters. Here you will learn what a vector value looks like when you write it, how PostgreSQL validates it, and how to load and change vectors safely at scale.
Writing a vector value
A vector value is written as a bracketed, comma-separated list of numbers. In SQL it is usually a string literal that PostgreSQL converts to the column type:
INSERT INTO items (content, embedding) VALUES
('a', '[1,2,3]'),
('b', '[4.5,-6,0.25]');The literal is parsed by the vector input function. Whitespace is tolerated and decimals and exponents such as 1e-3 are accepted. Internally each element is stored as a 4-byte single-precision float, so values are rounded to real precision. If your application computes embeddings in double precision, expect small differences after a round trip.
The type also has explicit conversions, which help when the values come from other SQL expressions:
SELECT '[1,2,3]'::vector;
SELECT ARRAY[1,2,3]::real[]::vector(3);
SELECT '{1,2,3}'::double precision[]::vector;What the database checks
Each insert goes through validation. The check that fails most often is the dimension count. A vector(3) column accepts only three-element vectors.
The errors look like this:
INSERT INTO items (content, embedding) VALUES ('bad', '[1,2]');
-- ERROR: expected 3 dimensions, not 2
INSERT INTO items (content, embedding) VALUES ('bad', '[1,NaN,3]');
-- ERROR: NaN not allowed in vectorA failing statement aborts the whole statement. In a multi-row INSERT, one malformed row means no rows are inserted. Inside a transaction, the transaction enters the aborted state until you roll back or use a savepoint.
Columns without a dimension
You can declare a column as plain vector with no dimension. It then accepts vectors of different lengths. That is flexible, but it has a cost. Indexes require a fixed dimension, and distance operators raise an error when you compare vectors of different lengths. Prefer vector(n) so that mistakes, such as switching embedding models, fail at insert time instead of at query time.
NULL and zero vectors
A vector column can be NULL, and a distance involving NULL is NULL. Rows with a NULL embedding are not returned in a useful position by nearest-neighbor queries and are not stored in vector indexes. If every row should have an embedding, add NOT NULL.
A zero vector such as [0,0,0] is valid. It has no direction, so its cosine distance to anything is NaN. If you plan to use cosine distance, reject or skip all-zero embeddings in your loading code.
Updating vectors
An update replaces the whole vector. You cannot change a single element in place with SQL assignment.
UPDATE items
SET embedding = '[2,2,2]'
WHERE id = 3;You can also compute a new value with vector arithmetic. The operators +, -, and * work element by element on two vectors of the same dimension. The avg() aggregate returns the mean vector of a group:
SELECT avg(embedding) FROM items;
UPDATE items
SET embedding = embedding + '[0.1,0.1,0.1]'
WHERE id = 1;Re-embedding when content changes
An embedding describes one version of the text. If you edit content and leave the old embedding, searches will match the old meaning. Update both columns in one statement so they cannot drift apart:
UPDATE items
SET content = 'a, revised',
embedding = '[1.2,2.1,2.9]'
WHERE id = 1;If you change embedding models, every stored vector must be regenerated. Vectors from different models are not comparable, even when the dimensions match.
Upserts
When your pipeline may see the same record more than once, use INSERT ... ON CONFLICT. This relies on a unique constraint, here the primary key.
INSERT INTO items (id, content, embedding)
VALUES (1, 'a', '[1,2,3.5]')
ON CONFLICT (id)
DO UPDATE SET content = EXCLUDED.content,
embedding = EXCLUDED.embedding;EXCLUDED refers to the row you tried to insert. This makes the load idempotent: running it twice leaves the same final state.
Loading many rows
Single-row inserts from application code are slow because each one is a network round trip. There are three better options, in increasing speed:
- Multi-row
INSERT ... VALUESstatements with a few hundred rows each. COPYin text or CSV format.COPYin binary format, which avoids converting floats to text and back. Client libraries such as the pgvector Python package support it.
A CSV COPY must quote the vector, because the vector text itself contains commas:
COPY items (content, embedding) FROM STDIN WITH (FORMAT csv);
d,"[7,8,9]"
e,"[0.5,0.5,0.5]"
\.From psql, use \copy to read a file on your own machine instead of the server's filesystem.
Load first, index afterward
For an initial bulk load, create the table, load the data, and then create the HNSW or IVFFlat index. Building an index over existing data is much faster than updating it row by row. IVFFlat also needs representative data present at build time, because it derives its cluster centers from the rows it sees. Chapter material on index building covers this in detail. For now, the rule is to avoid creating the index before a large initial load.
Updates and indexes
PostgreSQL uses MVCC (multi-version concurrency control). An UPDATE writes a new row version and leaves the old one until VACUUM removes it. Vectors are large, since a 1536-dimension vector occupies about 6 KB. Frequent updates therefore create a lot of dead data.
Vector indexes follow the table. Each new row version is added to the index, and the old entry is cleaned up only after vacuum. Heavy update workloads lead to table bloat and slower scans. Two practical consequences:
- Update an embedding only when it actually changed. An
UPDATEthat rewrites the same value still creates a new version. - Make sure autovacuum keeps up, and run
VACUUMmanually after a very large batch of updates or deletes.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `expected 3 dimensions, not 2` | Literal length differs from `vector(n)` | Check the embedding model's output size and the column definition |
| `NaN not allowed in vector` | Upstream computation produced NaN | Validate vectors before sending them |
| `invalid input syntax for type vector` | Missing brackets or stray characters | Use `[a,b,c]`, not `(a,b,c)` or `{a,b,c}` |
| CSV `COPY` splits the vector into columns | Vector not quoted | Wrap the vector in double quotes |
| Cosine search returns `NaN` for some rows | Zero vectors stored | Filter them out at load time |
Exercise
A table has a column embedding vector(3). You run a single INSERT with 1,000 rows, and row 640 contains '[1,2]'. How many rows are inserted, and why?
Show answer
None. The dimension check raises "expected 3 dimensions, not 2" for row 640, and a failed statement is rolled back as a whole. Fix or remove the bad row and rerun, or validate in the client before sending.
Exercise
Write a statement that inserts the row (id 10, content 'z', embedding [0,0,1]) or, if id 10 already exists, replaces both content and embedding with the new values.
Show answer
INSERT INTO items (id, content, embedding) VALUES (10, 'z', '[0,0,1]') ON CONFLICT (id) DO UPDATE SET content = EXCLUDED.content, embedding = EXCLUDED.embedding;