Sub topic 4
The vector type and fixed dimensions
Assume you know basic PostgreSQL commands such as CREATE TABLE, INSERT, and SELECT. You should also understand that an embedding is a list of numbers produced from text, images, or other data.
A pgvector vector is a PostgreSQL value that stores an ordered list of floating-point numbers. The number of values is the vector's dimension. For example, [0.2, -0.1, 0.8] has three dimensions.
Declaring a fixed-size vector column
Use vector(n) when every value must contain exactly n numbers:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (
id bigserial PRIMARY KEY,
body text NOT NULL,
embedding vector(3) NOT NULL
);The embedding column accepts three-dimensional vectors only. The dimension usually comes from the embedding model. If a model produces 768 numbers, declare the column as vector(768).
A fixed dimension protects the table from incompatible data. It also gives vector indexes a consistent shape and makes distance comparisons meaningful.
INSERT INTO documents (body, embedding) VALUES
('first document', '[0.10, 0.20, 0.30]'),
('second document', ARRAY[0.40, 0.50, 0.60]::vector);
-- This fails because the vector has only two dimensions.
INSERT INTO documents (body, embedding)
VALUES ('invalid document', '[0.10, 0.20]');The text form uses square brackets and comma-separated numbers. PostgreSQL can also convert an array to vector, as shown in the second row.
Updating and checking vectors
An update must also provide the declared number of dimensions:
UPDATE documents
SET embedding = '[0.15, 0.25, 0.35]'
WHERE id = 1;
SELECT id, vector_dims(embedding) AS dimensions
FROM documents;vector_dims returns the number of components. vector_norm returns the Euclidean length of a vector, which can help diagnose unexpected values.
A column declared as vector without a dimension can store vectors with different lengths. That is useful when data arrives from several models, but it weakens validation. Similarity operations and indexes generally require comparable dimensions, so a fixed declaration is the safer choice for one search collection.
Choosing the dimension
| Source | Result | Database choice |
|---|---|---|
| Model produces 3 values | 3 dimensions | `vector(3)` |
| Model produces 768 values | 768 dimensions | `vector(768)` |
| Multiple model sizes | Varies | Separate columns or tables |
Keep vectors from different models in separate columns or tables unless you have a deliberate conversion step. A database constraint can prevent accidental mixing, but it cannot determine whether two models have compatible meanings.
Exercise
What happens when you insert a two-dimensional vector into a column declared as vector(3), and why is that useful?
Show answer
PostgreSQL rejects the row because the value has the wrong dimension. This prevents incompatible embeddings from entering a collection that will later be compared or indexed together.