Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Engineering~9 min readComparison
Head to Head

SQL vs vector database: exact match, or nearest neighbor?

SQL / RelationalvsVector DB

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.

01

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.

→ The rule

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.

02

Head to head

DimensionSQL / RelationalVector Database
Core queryExact match, range, join, aggregateNearest-neighbor similarity
Data shapeStructured rows & columnsHigh-dimensional embedding vectors
IndexB-tree, hash, bitmapHNSW, IVF, PQ (ANN)
ResultExactly the matching rowsApproximate top-k nearest
Question it answers"Which rows meet these conditions?""Which items are most like this?"
Transactions / joinsStrong (ACID, foreign keys)Limited — built for search, not relations
Typical useOrders, users, inventory, analyticsSemantic search, RAG, recommendations
ExactnessExact by designApproximate — trades recall for speed
03

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
04

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.

→ The cheap default

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.

05

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.

→ The trade you’re actually making

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.

06

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.

→ The pattern generalizes

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

The picture: an exact walk and an approximate one

B-tree: WHERE price < 50 50 20 | 35 80 | 120 12 18 22 31 38 47 descend log N levels,then scan the leaves exact and complete HNSW: nearest to q in a b c q greedy hops toward qapproximate top-k
The B-tree follows keys, so it can prove it found every row under 50: it descends to the first match and reads leaves in order until the keys pass 50. The graph follows distances: at each node it moves to the neighbour closest to 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.
By the numbers

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.

StrategyWork per queryValid results (expected)What you get
SQL filter onlyIndex lookup on the two columns20,000 rowsThe exact set, with no notion of “most like this”
ANN top 10, then filter10 candidates10 × 0.02 = 0.2Usually zero results
ANN top 100, then filter100 candidates2A short, half-empty page
ANN top 500, then filter500 candidates10 on averageA 45.7% chance of fewer than 10
Filter first, then exact scan20,000 × 768 = 15.36M multiply-adds10The exact top 10 within the filter; 50× less work than scanning all 1M
Filter inside the ANN searchSmall, if the engine supports it10The 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.

Trade-offs

Cost and trade-offs, index by index

CaseTimeSpaceWhy
B-tree lookup or rangeO(log N + matches)O(N) index entriesExact and ordered. Serves =, <, BETWEEN, ORDER BY and joins.
Full table scanO(N)NoneWhat a WHERE does with no usable index. Slow, but still exact.
Flat vector scanO(N · d)1M × 768 dims × 4 bytes = 3.07 GB as float32Exact nearest neighbours, and the ground truth for measuring an ANN index.
HNSWSub-linear; roughly logarithmic in practiceVectors plus neighbour links per node, best kept in RAMApproximate. A search-breadth setting trades recall for latency; builds are much slower than a B-tree’s.
IVFScans only the closest few of many clustersVectors plus one centroid per clusterApproximate. Misses neighbours just across a cluster boundary unless it probes more clusters.
Product quantizationDistances computed on compressed codes3,072 bytes per vector → a 96-byte code: 32× smaller, 96 MB per millionLossy. 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.

Watch for

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_search of 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.

In the wild

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).

Your call

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.

You already run Postgres and your vector workload is modest — a few hundred thousand embeddings.

What is the fundamental difference in what the two return?

Frequently asked

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.

SQL vs Vector Database · Vibe Engines · 2026
Finished this one? 0 / 209 Handbooks done
NextRAG vs Long Context Next on the “Retrieval” ladder · rung 6 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks