Learning objectives
After reading this article you will be able to:
- Understand what changes between pgvector and a dedicated vector database
- Write pgvector queries and HNSW and IVFFlat indexes
- Recognize the signs that it is time to migrate
When a project adds semantic search or RAG, the question comes up: put the embeddings in the PostgreSQL you already have, with the pgvector extension, or stand up a database built only for vectors? Both store vectors and find nearest neighbors. The difference is in what comes with them: transactions, JOINs and one less system on one side; distribution, filtering built into the index and ready-made search features on the other.
If distance and approximate indexes are still new terms, start with what is a vector database and what are embeddings.
What is each option?#
pgvector is an open source extension for PostgreSQL. It adds vector types (single-precision, half-precision, binary and sparse), distance operators (L2, inner product, cosine, L1, Hamming and Jaccard) and two approximate indexes, HNSW and IVFFlat. The vector becomes a column like any other, and you keep what PostgreSQL already gives you: ACID transactions, point-in-time recovery and JOINs.
A dedicated vector database is a server built around vector search. It comes in three shapes:
- Open source, on your own server: Qdrant, Milvus, Weaviate and Chroma are among the best-known projects. Some also run as a cluster.
- A cloud service run by the vendor: several of these projects have a hosted version from the vendor itself, and there are proprietary services such as Pinecone.
- Embedded in the application: Chroma, for example, runs in memory inside the Python process, which helps with prototypes.
What are the differences, side by side?#
| Criterion | pgvector in PostgreSQL | Dedicated vector database |
|---|---|---|
| Where vectors live | In the same table as your data | In a separate system with its own schema |
| Consistency | Text and vector written in the same transaction | Keeping two databases in sync is on you |
| Filtering | SQL WHERE and JOINs; with an approximate index, the filter runs after the scan |
In some projects, the filter is part of the index itself |
| Indexes | HNSW and IVFFlat | HNSW, IVF, on-disk and GPU indexes, depending on the project |
| Distribution | Vertical on one server; replicas and sharding with PostgreSQL tools | Native sharding and replication in several projects |
| Hybrid search | With PostgreSQL full-text search, combined by you | Built into some projects (BM25 keywords plus vectors) |
| Operations | No new system to monitor and upgrade | One more server, with its own backups, versions and network |
| Learning curve | The SQL you already use | A new API and concepts (collections, payloads) |
What does pgvector look like in practice?#
With the extension enabled in the database (installation depends on where PostgreSQL runs; the project's README lists the options), the table gets a vector column with your embedding model's number of dimensions. The example uses 3 dimensions to fit on screen; real models use hundreds or thousands. The full flow, from embedding to answer, is in how to build a RAG chatbot with PostgreSQL and pgvector.
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
document_id bigint NOT NULL,
language text NOT NULL,
content text NOT NULL,
embedding vector(3) NOT NULL
);
INSERT INTO chunks (document_id, language, content, embedding) VALUES
(1, 'en', 'Refunds within 7 days.', '[0.9,0.1,0.0]'),
(2, 'en', 'Support Monday to Friday.', '[0.1,0.8,0.2]'),
(3, 'es', 'Reembolsos en 7 días.', '[0.88,0.12,0.01]');
-- the 5 nearest neighbors by cosine distance (<=>)
SELECT id, content, embedding <=> '[0.85,0.15,0.0]' AS distance
FROM chunks
WHERE language = 'en'
ORDER BY embedding <=> '[0.85,0.15,0.0]'
LIMIT 5;Each distance has its operator: <-> for L2, <#> for (negative) inner product, <=> for cosine and <+> for L1. Without an index, the query does exact search against every row: perfect results, at a cost that grows with the table.
An approximate index trades some recall for speed. The index's operator class has to match the query's distance:
-- HNSW: multilayer graph, can be created on an empty table
-- m = 16 and ef_construction = 64 are the defaults
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- more candidates per search: more recall, less speed (default 40)
SET hnsw.ef_search = 100;
-- the alternative, IVFFlat: create it after loading the data
-- lists: start with rows / 1000 (up to 1M rows)
CREATE INDEX ON chunks USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
-- probes: start with the square root of lists (default 1)
SET ivfflat.probes = 10;HNSW has the better speed-recall tradeoff, but it uses more memory and builds more slowly, and builds are much faster when the graph fits in maintenance_work_mem. IVFFlat builds faster and uses less memory, with weaker queries. Both index vectors of up to 2,000 dimensions; with the half-precision halfvec type, the index goes up to 4,000.
What happens to filters?#
This is the most technical difference. In pgvector, with an approximate index, the WHERE filter is applied after the index scan. The README gives the example: if a condition matches 10% of rows, with HNSW and the default ef_search of 40, only 4 rows come back on average, even if you ask for LIMIT 10.
The project itself offers ways out:
- Iterative index scans, from pgvector 0.8.0: with
SET hnsw.iterative_scan = strict_order;(orrelaxed_order, which allows slightly out-of-order results for better recall), the index keeps scanning until it finds enough results or hits thehnsw.max_scan_tuplesceiling (20,000 by default). - A regular index on the filter column, a B-tree for instance: when the filter is selective, PostgreSQL can use it and do exact search only on the rows that pass.
- A partial index, for a few distinct values:
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops) WHERE (language = 'en'); - Table partitioning, when there are many distinct values.
Dedicated databases tackle the problem inside the index. Qdrant, for example, indexes each point's metadata (the payload) and adds filter-aware edges to the HNSW graph, as long as the payload indexes exist before the graph is built. With many tenants in the same collection and combined filters, that difference can be decisive.
How does each one grow, and how much work is it?#
The pgvector README is blunt: scale pgvector the way you scale PostgreSQL. Vertically, more memory, CPU and storage on one instance. Horizontally, replicas or sharding with tools such as Citus. To shrink the working set, it suggests halfvec for tables and binary quantization for indexes, with re-ranking at the end.
Vectors take space: each one uses 4 bytes per dimension as vector and 2 as halfvec, plus 8 bytes. A million 1,536-dimension vectors add up to about 6 GB of single-precision data alone, before the index. The math for a full corpus is in how much a RAG system costs.
Dedicated databases are built to distribute. Qdrant has a distributed mode in which collections are split into shards and replicated across nodes. Milvus runs as a Python library (Milvus Lite), as a single server or as a Kubernetes cluster, and its documentation mentions tens of billions of vectors in the largest deployments. They also ship quantization: in Qdrant, scalar quantization turns each 32-bit number into an 8-bit integer and cuts a vector's memory by a factor of 4.
The price is running one more system: another server to monitor, another backup routine, another version to upgrade and, above all, keeping the main database and the vector one in sync. When a document is deleted in PostgreSQL, something has to delete the vector on the other side. With pgvector, a foreign key with ON DELETE CASCADE handles it in the same transaction.
When should you migrate from pgvector to a dedicated database?#
Start with pgvector if you already use PostgreSQL. Consider migrating when measured, not theoretical, signs show up:
- The index no longer fits in the server's memory and latency climbs, even with
halfvecand quantization. - Filters wreck recall: queries with
WHEREreturn fewer rows than theLIMIT, and neither iterative scans nor partial indexes fix it. - Vector search competes for resources with the rest of the application's queries, and splitting the load is worth more than tuning the server.
- You need something the dedicated project already ships, such as built-in hybrid search, native sharding or on-disk indexes for billions of vectors.
Migrating is simpler than it sounds, because the data is an id, a vector and some metadata. The care is to keep the same embedding model and the same distance metric and to rebuild the index at the destination. Before migrating, run EXPLAIN ANALYZE on the slow queries: sometimes all that is missing is the right index, or ef_search is too low. To see when a relational database is enough, also read PostgreSQL vs MySQL and which database to choose.
How to do this on Square Cloud#
Square Cloud has no dedicated vector database, but its PostgreSQL hosting, from the Standard plan (R$44.99 a month), comes with the pgvector and pg_cron extensions. The vectors can live in the same database as your documents and metadata, and pg_cron schedules SQL jobs, such as deleting old chunks, inside the database itself. You create the database in the dashboard (name, memory and engine), it is ready in seconds in the same datacenter as your applications, with about 1 ms of average latency, and the minimum for PostgreSQL is 1024 MB. Hobby does not include databases.
Plan around the real limits: the instance is fixed and single-node, with up to 256 connections per database and no pooler in front, so choose the database's memory with the index size in mind. Connections require TLS: the client trusts the CA downloaded from the dashboard and, on PostgreSQL, also presents the certificate. Databases get an automatic daily snapshot, kept for 7 days, and you can take a manual snapshot before rebuilding an index.
If search outgrows what one server delivers, an external vector service is still an option. See the details on PostgreSQL hosting.
AI
Host AI apps in always-on containers
FAQs
Is pgvector a vector database?
It is an open source extension that adds vector types, distance operators and approximate indexes to PostgreSQL. With it, your relational database also does vector search, in the same table and the same transaction.
What is the difference between HNSW and IVFFlat?
HNSW builds a multilayer graph, has the better speed-recall tradeoff and can be created on an empty table, but it uses more memory and builds more slowly. IVFFlat divides vectors into lists, builds faster and uses less memory, but it should be created after the table has data.
What is pgvector's dimension limit?
The vector type stores up to 16,000 dimensions, but HNSW and IVFFlat indexes only accept vectors of up to 2,000. With the half-precision halfvec type, the index goes up to 4,000 dimensions, and with the bit type, up to 64,000.
Why does my search with WHERE return fewer rows than the LIMIT?
With an approximate index, pgvector applies the filter after scanning the index. If the filter discards most candidates, few rows remain. Turn on iterative index scans (hnsw.iterative_scan) or create a partial index for the filter.
More in AI
See all 31 articles- How much does an AI chatbot cost to build and run?Running an AI chatbot costs model tokens, hosting, a database and, with RAG, extra context per message. See how to estimate the cost per conversation.
- How much does a RAG system cost? Embeddings, database and LLMA RAG system has three costs: embeddings, a vector database and the LLM. See the math for 1,000 questions a day, with hypothetical prices, and where the bill grows.
- RAG vs fine-tuning: which to useRAG puts your data in the prompt at question time; fine-tuning changes the model's weights with examples. Compare cost, updates, latency and when to use each.
- 429 errors from an AI API: rate limits, quota and how to handle themA 429 from OpenAI, Claude or Gemini means a rate limit or exhausted quota. Learn to tell them apart, read the limit headers and retry with backoff.