Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
SQL vs vector database: exact match, or nearest neighbor?
A relational database is built to answer 'which rows exactly match these conditions?' A vector database is built to answer 'which items are most similar to this one?' Those are different questions with different math underneath — and the reason RAG and semantic search needed a new kind of database, not just a new query.
The one distinction that decides everything
A relational (SQL) database stores structured rows and answers exact and range queries — WHERE status = 'paid' AND price < 50 — using indexes like B-trees that are built for precise lookups, sorting and joins. A vector database stores high-dimensional embeddings and answers similarity queries — "find the 10 vectors closest to this one" — using approximate-nearest-neighbor indexes like HNSW or IVF. One finds rows that match a condition; the other finds items that are semantically near a query, where "near" means small distance in embedding space, not equality.
If your query is a precise condition (equals, greater-than, in a set, joined across tables), you want SQL. If your query is "most like this" over fuzzy, unstructured meaning (text, images, audio turned into vectors), you want vector search. They answer categorically different questions.
Head to head
| Dimension | SQL / Relational | Vector Database |
|---|---|---|
| Core query | Exact match, range, join, aggregate | Nearest-neighbor similarity |
| Data shape | Structured rows & columns | High-dimensional embedding vectors |
| Index | B-tree, hash, bitmap | HNSW, IVF, PQ (ANN) |
| Result | Exactly the matching rows | Approximate top-k nearest |
| Question it answers | "Which rows meet these conditions?" | "Which items are most like this?" |
| Transactions / joins | Strong (ACID, foreign keys) | Limited — built for search, not relations |
| Typical use | Orders, users, inventory, analytics | Semantic search, RAG, recommendations |
| Exactness | Exact by design | Approximate — trades recall for speed |
When to use each
Reach for SQL
- Transactional data: orders, payments, inventory, users
- Exact filters, ranges, and multi-table joins
- Aggregations and analytics (counts, sums, group-by)
- Anything needing ACID guarantees and referential integrity
- Reporting where every matching row must be returned
Reach for a vector database
- Semantic search over text, images or audio
- Retrieval for RAG — finding relevant chunks by meaning
- Recommendations and "more like this"
- Deduplication and near-duplicate detection
- Any lookup by similarity rather than exact value
The answer is usually "both, with a filter"
Real systems rarely pick one. A semantic search almost always needs both similarity and exact constraints: "find documents similar to this query and owned by this user and updated this year." That’s vector similarity plus SQL-style filtering, together. So the two worlds have been converging from both directions: vector databases added scalar metadata filtering so you can constrain a similarity search, and relational databases grew vector extensions (Postgres’ pgvector is the common one) so you can store embeddings next to your rows and do nearest-neighbor search in the same database as your joins.
If you already run Postgres and your vector workload is modest, pgvector keeps everything in one database — no new system, and filters + similarity in one query. Reach for a dedicated vector database when the vector workload gets large or latency-critical enough that a purpose-built ANN engine earns its operational cost.
Why the line is blurrier than it looks
"SQL vs vector" sounds like a hard fork, but in practice it’s a spectrum. On one end, a dedicated vector database (Pinecone, Milvus, Qdrant, Weaviate) is optimized purely for ANN search at scale and adds metadata filters on top. On the other, a relational database with a vector extension keeps your embeddings, rows, transactions and joins in one place and does "good enough" ANN for many workloads. The real decision isn’t "relational or vector" — it’s "is vector search my primary, high-scale workload, or a feature bolted onto mostly-relational data?"
The one thing that doesn’t blur is the query semantics. Vector search returns approximate nearest neighbors — it deliberately trades a little recall for a lot of speed, so it can miss a true match — while a SQL WHERE is exact and complete. If your task genuinely needs "every row that matches, guaranteed," that’s a relational query no ANN index should be answering, whichever database it physically lives in.
SQL gives exactness, transactions and joins over structured data. Vector search gives similarity over unstructured meaning, at the cost of being approximate. The architecture question is which one is primary; the query question is which one each individual lookup actually needs.
A worked scenario: an e-commerce product catalog
Your store’s backbone is unmistakably relational: orders, payments, inventory counts, prices and user accounts all demand exact queries, joins and ACID transactions — you cannot have "approximately charged the customer." SQL owns this, and no vector database should be anywhere near your ledger.
But the feature "customers who liked this also liked…" and the search box that understands "warm waterproof hiking jacket" are similarity problems: embed the products and queries, and find nearest neighbors. Crucially, that similarity search still needs relational-style filters bolted on — in stock, ships to this country, under this price. So you either add pgvector to the Postgres you already run (embeddings beside the product rows, filters and similarity in one query) or, at large scale, stand up a dedicated vector database that indexes the catalog and applies metadata filters. Either way you end up running both kinds of query — the only choice is whether they live in one database or two.
Transactional, exact, relational data → SQL. Similarity over unstructured meaning → vector search. Almost every AI feature needs a filtered similarity query, which is exactly why the two are converging rather than competing.
The picture: an exact walk and an approximate one
q and stops when none is closer. That is fast, and almost always right, but a true nearest neighbour reachable only by a different route can be missed.Worked example: one filtered similarity query, five ways
Take the page’s catalog at an illustrative size: 1,000,000 products with 768-dimensional embeddings. The query wants the 10 products most similar to “warm waterproof hiking jacket” that are in stock and ship to the UK. That filter matches 2% of rows: 20,000. For the expected counts below, assume the filter is unrelated to similarity, the simplest case; real filters are often correlated, which can make things better or much worse.
| Strategy | Work per query | Valid results (expected) | What you get |
|---|---|---|---|
| SQL filter only | Index lookup on the two columns | 20,000 rows | The exact set, with no notion of “most like this” |
| ANN top 10, then filter | 10 candidates | 10 × 0.02 = 0.2 | Usually zero results |
| ANN top 100, then filter | 100 candidates | 2 | A short, half-empty page |
| ANN top 500, then filter | 500 candidates | 10 on average | A 45.7% chance of fewer than 10 |
| Filter first, then exact scan | 20,000 × 768 = 15.36M multiply-adds | 10 | The exact top 10 within the filter; 50× less work than scanning all 1M |
| Filter inside the ANN search | Small, if the engine supports it | 10 | The predicate is checked during the graph walk |
Over-fetching (top 500 for 10 results) only works on average: the count of valid hits is binomial, and with 500 tries at 2% it falls short of 10 almost half the time. Filtering first is exact and, at 2%, cheap. But its cost grows with the filter: at 50% selectivity the same exact scan is 384M multiply-adds and the ANN index wins again. Choosing between those plans per query is exactly what a query planner does, and it is why filter-aware vector engines check how selective a filter is before deciding how to search. When the filter is very selective, a graph walk restricted to matching nodes can also strand itself, so many engines switch to a filtered exact scan below some threshold.
Cost and trade-offs, index by index
| Case | Time | Space | Why |
|---|---|---|---|
| B-tree lookup or range | O(log N + matches) | O(N) index entries | Exact and ordered. Serves =, <, BETWEEN, ORDER BY and joins. |
| Full table scan | O(N) | None | What a WHERE does with no usable index. Slow, but still exact. |
| Flat vector scan | O(N · d) | 1M × 768 dims × 4 bytes = 3.07 GB as float32 | Exact nearest neighbours, and the ground truth for measuring an ANN index. |
| HNSW | Sub-linear; roughly logarithmic in practice | Vectors plus neighbour links per node, best kept in RAM | Approximate. A search-breadth setting trades recall for latency; builds are much slower than a B-tree’s. |
| IVF | Scans only the closest few of many clusters | Vectors plus one centroid per cluster | Approximate. Misses neighbours just across a cluster boundary unless it probes more clusters. |
| Product quantization | Distances computed on compressed codes | 3,072 bytes per vector → a 96-byte code: 32× smaller, 96 MB per million | Lossy. Re-score the shortlist with full vectors when recall matters. |
For most teams the first wall is memory, not CPU. A B-tree on a price column is a few bytes per row; 768 floats are 3,072 bytes per row before any index overhead, and at 10M rows that is 30.72 GB. That number, more than query speed, is usually what pushes a workload out of the main database and into a dedicated engine.
Common mistakes
- Filtering after the ANN search
The pgvector README spells this out: with an HNSW index, filtering is applied after the index scan, and at the default
hnsw.ef_searchof 40, a condition matching 10% of rows returns about 4 rows on average. The query succeeds and silently returns too few. Raise the search breadth, use the engine’s filtered or iterative scan, partition by the filter column, or fall back to an exact scan for selective filters. - A distance metric that does not match the index
In pgvector,
<->is L2,<=>is cosine and<#>is negative inner product, and an index built for one operator is not used by the others: the query falls back to a sequential scan and gets slow without failing. For unit-length vectors all three give the same ranking, so normalising the embeddings removes one way to get this wrong. - Treating the vector copy as the source of truth
Embeddings are derived data. When a row is edited, deleted or has its permissions changed, the vector must change too, or a deleted document keeps turning up in answers. Next to the row in Postgres, one transaction can update both. In a separate vector store you need an outbox or change-data-capture pipeline, and a plan for the lag.
- Never measuring recall
Default index settings are a starting point, not a guarantee. Take a sample of real queries, compute the exact top 10 with a flat scan, compare it with the ANN top 10, and count the overlap: 9 shared results is a recall@10 of 0.9. Re-check after the data grows, because recall can drift as the index fills.
- Sizing by row count instead of bytes
“Only a million rows” sounds small until you multiply: 1M × 768 × 4 bytes is 3.07 GB of raw vectors that an HNSW index wants in memory. Smaller embedding dimensions, half-precision storage or quantization each cut that, and each costs some accuracy, so decide with a recall measurement, not by guessing.
Where this shows up in production and interviews
- Postgres plus pgvector
The common first step for adding RAG or semantic search to an existing app: an embedding column next to the rows it describes, joins to the permission tables, and one transaction that keeps them in sync. Most of the mistakes above surface here first, because the database looks familiar while the index behaves differently.
- Dedicated vector databases
Pinecone, Milvus, Qdrant and Weaviate earn their place when vectors are the main workload: large collections, tight latency targets, and filter-aware search built into the engine. The price is a second system to keep consistent with the first.
- Multi-tenant RAG
Every tenant’s query must only see that tenant’s documents. A tenant filter applied after the ANN search fails two ways at once: too few results for small tenants, and a design where one missing filter leaks data. Apply it before or during the search, or give each tenant its own partition or namespace.
- The interview version
Expect “do we need a vector database?” (do the memory arithmetic, then decide), “how do you combine a filter with similarity?” (pre-filter vs post-filter, and why post-filtering returns too few), and “how do you know the index is good enough?” (recall@k against a flat scan).
Which would you pick?
Three situations. Pick the side you'd actually build — the explanation follows.
Find documents similar in meaning to a user's question, restricted to one tenant and the last 30 days.
This is the shape almost every AI feature has: exact predicates plus fuzzy similarity. Filtering after retrieval means the top-k was chosen before the constraint was applied, so you can end up with too few valid results or none. Full-text matching does not capture "similar in meaning", which was the requirement.
You already run Postgres and your vector workload is modest — a few hundred thousand embeddings.
At modest scale the deciding cost is operational, and adding a second datastore means another system to run, back up, secure and keep consistent with the first. A specialised index matters at a scale you are not at, and "we will grow into it" pays that cost today for a benefit that is speculative.
What is the fundamental difference in what the two return?
Approximation is the point, not a limitation: ANN indexes trade exactness for the ability to search millions of vectors quickly, so results are "very likely the closest" rather than provably so. Treating vector search as merely another index hides that trade — and it is the trade that determines when each tool is appropriate.
Quick answers
What's the difference between a SQL and a vector database?
A relational (SQL) database stores structured rows and answers exact and range queries with indexes like B-trees — ideal for transactions, filters and joins. A vector database stores embeddings and answers similarity queries with approximate-nearest-neighbor indexes like HNSW — ideal for semantic search, RAG and recommendations. One finds rows that match a condition; the other finds items most similar to a query.
Do I need a vector database for RAG?
You need vector similarity search, but not necessarily a separate database. If your corpus is modest and you already run Postgres, the pgvector extension stores embeddings next to your rows and does nearest-neighbor search in the same database. A dedicated vector database earns its cost when the vector workload becomes large or latency-critical enough to justify a purpose-built ANN engine.
Can a SQL database do vector search?
Yes — extensions like pgvector for Postgres add vector columns and approximate-nearest-neighbor indexes, so you can store embeddings alongside relational data and run similarity search plus SQL filters in one query. It handles many workloads well; dedicated vector databases specialize in ANN at very large scale.
Is vector search exact?
No. Vector databases return approximate nearest neighbors — they deliberately trade a little recall for a large speed gain, so they can occasionally miss a true match. A SQL WHERE clause is exact and complete. If a lookup genuinely needs every matching row guaranteed, that is a relational query, not an approximate similarity search.
This idea in other formats
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- Concurrency, Locks & Isolation LevelsHow overlapping operations stay correct — race conditions, optimistic vs pessimistic locking, the four isolation levels and their anomalies, MVCC, and distributed locks with fencing tokens. Part of System Design Fundamentals.Read →
- Partitioning, Sharding & ReplicationHow one dataset becomes many — range vs hash partitioning, consistent hashing and virtual nodes, hot partitions, replication topologies, replication lag, and quorums. Part of System Design Fundamentals.Read →
- The SQL HandbookWhat the database does underneath your SELECT — the relational model and keys, joins (inner/left/right/full), indexes and B-trees, the query planner and reading EXPLAIN, transactions and ACID, isolation levels and the anomalies they prevent, normalization vs denormalization, and the pitfalls (N+1, missing indexes, SELECT *).Read →
- The PostgreSQL Internals HandbookUPDATE never updates, and a janitor keeps it working. Heap pages and tuples, MVCC's row versions (xmin/xmax visibility arithmetic), VACUUM, bloat and the wraparound scare, B-trees, HOT updates and index-only scans, the WAL's three superpowers (recovery, replication, PITR), reading the planner honestly, and why PgBouncer is infrastructure.Read →
- SQL vs NoSQLFramed as a war, it’s really a menu. Relational databases give you schema, joins and ACID; NoSQL is an umbrella of document/key-value/wide-column/graph stores that drop some of that for flexibility and horizontal scale. The relationships-vs-scale core difference, the CAP trade-off, and why to start relational.Read →
- PostgreSQL vs MySQLBoth are excellent free relational databases you can build a company on, so the choice is about character, not capability: Postgres prizes correctness, rich types and advanced features; MySQL prizes simplicity and read-heavy speed. The real differences, when each wins, and why Postgres became the modern default.Read →