Multi-Modal Reasoning: Combining AI Vectors with Standard SQL
local graph
Chapter 17 — Multi-Modal Reasoning: Combining AI Vectors with Standard SQL
Section titled “Chapter 17 — Multi-Modal Reasoning: Combining AI Vectors with Standard SQL”Multi-Modal Reasoning: Combining AI Vectors with Standard SQL
Section titled “Multi-Modal Reasoning: Combining AI Vectors with Standard SQL”As AI workloads become mainstream, they pose a new challenge for databases. In the age of AI, databases don’t just store data and handle business transactions; they must also understand the meaning of the polymorphic content they store and leverage its semantics to derive new insights.
As we saw in the previous chapter, vectors are a powerful tool for capturing the embedded meaning of data, and vector-based calculations are the building blocks for recommendation engines and many other applications that rely on AI-based semantic processing.
In this chapter, we will show that combining semantic, AI-based processing with relational operations in PostgreSQL creates a unified reasoning engine capable of powering search, personalization, anomaly detection, recommendations, and AI-assisted decision systems at scale.
We will explore multi-modal reasoning, high-performance hybrid query designs, indexing strategies, ranking models, real-world use cases, and their architectural implications. By the end, you will understand why SQL and vectors belong together—and why separating them into different systems introduces unnecessary complexity, cost, and cognitive overhead.
This chapter covers the following topics:
- The power of multi-modal reasoning
- The reasons why vectors and SQL data belong on the same platform
- Guidelines for designing hybrid queries encompassing vectors and SQL data
- Real-world examples
- An architectural discussion of simpler systems with unified governance
The power of multi-modal reasoning
Section titled “The power of multi-modal reasoning”Vector databases introduced a radical new capability: machines can now work with meaning. Vectors are used to store and process the embedded semantics (a.k.a. meaning) of data, words, texts, and pictures.
Vectors turn words, descriptions, and context into math, making “similarity” something we can compute. Instead of matching exact numbers and words, we can match intent, tone, and concept—even when the wording differs.
But meaning alone is not enough, because similarity is only the first step. Real systems don’t just find things. They must decide what’s valid, safe, available, and relevant right now.
A result that is a semantically perfect match, but out of stock, out of region, overpriced, or recalled is not intelligence—it’s friction wearing a lab coat.
Imagine asking the system: ” Show me men’s attire for a formal occasion.” A vector database will return items with semantically similar descriptions. It will find items with the same use case (formal occasion), comparable features (men’s attire), or a matching style (formal) because their embeddings sit close together in vector space.
But real applications do not stop there. They ask for the following:
- Men’s attire for a formal occasion, and in stock: Similarity is nice, but inventory is a hard requirement in e-commerce. The customer can only purchase what is available now, so the query must join the inventory table and filter for sellable items.
- Men’s attire for a formal occasion priced below $ 500: Meaning has no budget. Customers do. The system must respect pricing constraints, often using current price rules (not expired ranges), promotions, and regional pricing logic.
- Men’s attire available in my region: Relevance isn’t global; it’s local. Shipping eligibility, warehouse coverage, regulatory constraints, and regional catalogs all shape what available truly means.
- Men’s attire, but only eco-certified models: Similar items aren’t always acceptable items. Certifications, compliance labels, and sustainability attributes are often stored as structured metadata—and must be enforced as hard filters.
In all the preceding scenarios, AI helped us identify products that matched the user’s intention, and SQL processing helped us connect with the business reality. That is multi-modal reasoning: blending semantic intelligence with relational decision-making.
What vectors bring to the table
Section titled “What vectors bring to the table”Chapter 16*,* Vectors and Indexing for AI with pgvector showed us that we can use vectors to convert the meaning of a sentence, for example, a product description or a support ticket, into a set of numbers that represent its meaning. Those numbers act as the semantic fingerprint.
The semantic fingerprint and AI-based vector calculations help us identify the following:
- Similarity of meaning: It helps the system recognize that “running shoes” and “jogging sneakers” are essentially the same idea, even though the words differ.
- Contextual relationship: It doesn’t just know what a word means—it also knows what tends to go with it. For example, it learns that “noise-canceling” often goes with “headphones,” or that “trail” often goes with “grip” and “water-resistant.”
- Latent structures: Vectors can pick up patterns that are hard to describe with rules, for example, grouping customer complaints that sound different but are actually the same issue. Or finding products that “look similar” when you use image vectors.
- Numerical representations for LLM reasoning: Modern AI (for example, LLMs) works with numbers. Vectors are a clean way to feed meaning into AI workflows—so the system can retrieve, compare, rank, and reason.
Vectors tell us what things feel similar to each other. This means that the system can find “close cousins” of a concept, not just exact keyword matches.
Vectors help us answer fuzzy questions, such as the following:
- “Show me products like this.”
- “Find similar issues in support tickets.”
- “What content matches the intent of this query?”
Vectors make the database less like a strict librarian and more like a helpful shop assistant who gets what you meant.
What SQL brings to the table
Section titled “What SQL brings to the table”If vectors are the database’s intuition (“this feels similar”), then SQL is its discipline (“only show what’s valid, allowed, and actionable”). SQL is the language that lets us ask clear, exact questions and get reliable, repeatable answers.
Here’s what SQL gives us:
- Precision filters: These act like checkboxes while shopping—only laptops under $500, only size 42, only in-stock. SQL does this with
WHEREconditions. - Strict conditions: Rules that must be true—not “close enough.” For example, price must be current, status must be
AVAILABLE, and region must beASIA. If it doesn’t match, it doesn’t show up. - Aggregations: SQL can summarize data, such as How many orders today? What’s the average price? Total sales by brand? Those are the
COUNT,AVG,SUM, and so on aggregations that we reviewed in Chapter 13*,* PostgreSQL’s Analytical Functions. - Groupings and rollups: These can organize summaries by categories, such as sales by city, issues by product line, and inventory by warehouse. These are the grouping operators discussed in Chapter 13*,* PostgreSQL’s Analytical Functions.
- Joins across diverse data: This is SQL’s superpower: connecting related information stored in different tables. For example, combine product, current price, inventory, brand, and country of origin into a single result. Without the
JOINoperators, we would have scattered facts. With joins, we get a complete story. - Security and governance: SQL can control who can see what. Row-level security is like saying, “You can see only your region’s customers.” Column-level security filters out properties you do not have access to.
- Auditing: The database audit log is like keeping a record of who asked what and when—essential for regulated industries and internal trust.
- Transactions and constraints: ACID-compliant transactions ensure updates happen safely—either everything succeeds or nothing changes. Constraints enforce rules on the data: the price cannot be negative, the product must have a price before it can be sold, and every product must have a unique ID.
- Decades of predictable performance behavior: SQL databases (especially PostgreSQL) have been optimized to handle large data volumes and traffic spikes. SQL provides mature tools: indexes, query plans, optimizers, monitors—stuff that keeps systems steady under pressure.
SQL answers specific questions and returns hard data. While vectors and AI help us find semantically similar items, SQL makes sure that the values are correct, secure, compliant, and usable in the real world.
Multi-modal reasoning: Vectors and SQL
Section titled “Multi-modal reasoning: Vectors and SQL”This is where things get interesting. Vectors help the system understand meaning; SQL ensures the answer fits hard-and-fast real-world rules. When we combine both techniques, practical magic happens, and “interesting results” become “results one can actually use.”
We can request, ” Find products similar to this description, but only ones that cost under $500 right now, only the eco-friendly versions, and rank them so the best matches and best value come first.”
This is what happens in simple terms:
- Vectors handle the ” similar to this ” part (like a smart assistant that understands intent)
- SQL handles the ” under $500,” ” price must be current,” and ” eco-certified only ” parts (like a strict store policy that keeps results honest)
- The ranking mixes both ” closest match ” and ” best deal ”
Or we can request, ” Show me products that match this query, but only electronics, only from this brand, and remove anything that has been recalled.”
This is what happens in simple terms:
- Vectors find items that feel related to your search
- SQL ensures you only see what’s relevant to the category, brand, and safety rules
- Recalled items are excluded, no matter how “similar” they are—because safety beats similarity
AI narrows the conceptual field. It reduces a huge catalog into “things that seem relevant.”
SQL sharpens the operational action. It applies the real constraints: price, availability, compliance, safety, region, and permissions, and allows the user to order, pay, and complete the purchase.
Multi-modal queries help us transform raw data into executable business decisions.
Why vectors and SQL belong in the same platform
Section titled “Why vectors and SQL belong in the same platform”When developing a modern system that combines AI-based processing and standard SQL queries, developers and architects grapple with whether embeddings and AI-based vector processing should reside in the central database, where conventional concepts such as products, prices, inventory, customers, and orders are managed, or whether AI processing should be delegated to a specialty system.
Many early AI-enabled projects chose to create a separate vector store for embeddings, nearest-neighbor calculations, and other AI processes. Choosing a specialty, best-of-breed, and innovative new technology sounded attractive, like buying a shiny new tool for a shiny new problem.
But here’s the catch: splitting data processing across multiple components fractures the architecture and comes with significant disadvantages. The split architecture creates the following:
- Two systems: One database for business data (products, prices, and customers), and another database for embeddings (meaning/similarity).
- Two consistency models: Data (e.g., products) must be updated in multiple places. When product descriptions change in the central database, do the corresponding embeddings change too? Suddenly, the truth can be out of sync.
- Two security models: Users, permissions, and audit rules must be maintained in multiple places. Someone might have access to embeddings but not to the actual data, or vice versa. That’s a governance headache.
- Two performance profiles: One system is fast for transactions and joins; the other one is fast for similarity search. But the real workload requires both together, which often means additional network calls and increased latency.
- Two failure domains: If either system slows down or fails, the whole application breaks or degrades. The split architecture doubled the places where things can go wrong. Backup and recovery, high availability, and zero-downtime patching become a nightmare.
- Two management domains:Two sets of licenses, two patch cycles, two skill sets, two backup and recovery procedures, and so on.
And then the human cost shows up:
- The data scientists generate embeddings in one system
- The application reads metadata (price, stock, and category) from another
- The operations team must run and monitor both
- Auditors must verify policies across two worlds
- Developers need to be trained in both technologies
- The system needs licenses and support for two technologies
That’s a lot of moving parts. A seemingly obvious decision to use best-of-breed technology has turned into a millstone, complicating everyone’s lives.
PostgreSQL’s extensible architecture allows us to avoid these problems. The pgvector extension introduced in Chapter 16*,* Vectors and Indexing for AI with pgvector makes it easy to store and work with AI vectors with up to 16,000 dimensions (and index up to 2,000 dimensions) in PostgreSQL, and to handle AI processing and standard SQL in the same transactional context, with the same tool, the same operational procedures, on the same hardware, and under the same permissive license.
Postgres eliminates the split. And when we remove the split, we remove a whole class of problems: sync jobs, mismatched security, extra latency, and “why are results wrong today?” investigations.
Locality wins
Section titled “Locality wins”Locality is a way of saying: keep related things together. If the product data (name, description, price, stock, and region) is in one place, and the product’s embedding (its meaning) is in another place, we are constantly shuttling information back and forth.
But when embeddings are stored alongside operational data in the same PostgreSQL database, life gets simpler and faster.
Here’s what that means in plain terms:
- No duplication: We don’t duplicate product details across two databases. This creates one source of truth. Less room for error, less mess.
- No sync jobs: We don’t need to create data pipelines or
cronjobs to keep the vector store up to date. No “Did the sync run?” panic at 2 AM. No, “We just updated the product descriptions for the Black Friday sale. Can you rerun the sync?” - No stale vectors: Stale means outdated. If a product description changes, its embedding should change too. Keeping them together makes it far less likely that the system is searching yesterday’s meaning using today’s SQL data.
- No cross-system custom code to merge search results: If all the data is in the same database, we can use
JOINto connect embedding, current price, inventory, and brand; there is no need for custom code to merge the SQL database results with the AI database results. If embeddings are elsewhere, you’re forced to do that connection across networks and application code: expensive to develop, slow, brittle, and hard to debug. - No complexity explosion: Two systems don’t just double the work, they multiply it: monitoring, run books, training, access control, backups, upgrades, failure handling, cost management, troubleshooting… all times two.
- Everything lives under one transactional umbrella: PostgreSQL treats the data and its embedding as a single, consistent unit. Transactions are always ACID-compliant, security rules are consistent, and queries can make decisions in a single shot.
In short, when meaning (vector data) and metadata (structured data) live together, the architecture stops fighting you.
Better consistency
Section titled “Better consistency”Consistency simply means the system should not disagree with itself, and consistency rules should be applied automatically. Any inconsistent transactions should be rejected immediately. Consistency is at the heart of the ACID definitions that we reviewed in Chapter 5*,* Transactions, ACID Compliance, and Data Normalization.
Embeddings (vectors) are created from SQL business data, such as product descriptions, customer notes, or incident reports, and they must stay in sync. Otherwise, if the SQL data changes but the embedding doesn’t, the search and recommendations start using obsolete meanings with the current SQL data, and the system becomes inconsistent.
PostgreSQL—and for that matter, any ACID-compliant relational database—helps address this problem:
- Product updates and embedding updates can be ACID-compliant, guaranteeing an all-or-nothing model. When we update a product description and regenerate its embedding, Postgres can ensure that both changes occur in the same transaction and become visible at the same time. This avoids inconsistencies where new descriptions co-exist with old embeddings.
- Security policies apply uniformly, ensuring that the same access rules protect both. If a user isn’t allowed to see specific products, customers, or logs, they also shouldn’t be able to search embeddings that indirectly reveal them.
- Audits and logs reflect a single reality, providing a single paper trail, a single timeline, and a single truth—no need to reconcile timestamps and merge log and audit data.
In short, PostgreSQL makes it much easier to keep meaning and data aligned, secure, and provable.
Better performance
Section titled “Better performance”Performance is mostly about one thing—how much work the system can do and how far the data must travel:
- Network hops are expensive: A network hop occurs when the app must jump from one system to another across the network (e.g., from your primary database to a vector database and back). Even if each hop is only milliseconds, it adds up fast, especially at scale.
- Streaming embeddings across systems is very expensive: Embeddings are big lists of numbers, and a single vector with 2,000 dimensions will take up 8 KB, even if the original description is on 256 characters! If you keep the embedding in a separate system, you often end up moving a lot of that data around, either for syncing, for searching, or for joining with business data. That creates bandwidth cost, latency, and operational pain.
When SQL and vectors run inside the same PostgreSQL engine, three good things happen:
- Distance calculations happen close to memory: The similarity math (how close two vectors are) happens right where the SQL data lives. There is no need to ship the embedding across the wire, which means less delay and less overhead.
- Filters prune candidate sets efficiently: The SQL planner can use statistics to quickly shrink the search space. For example, by applying SQL filters first (
category = Electronics, currentprice<$500, in stock, region = ASIA), and then computing similarity only on the smaller dataset. - Join operations avoid cross-system latency: Real answers usually require joins across multiple datasets: embeddings, products, current prices, available inventory, and other attributes. If vectors are in another system, you’re forced to do slow, awkward “joins” in application code. If everything is in PostgreSQL, joins are local and fast: one query, one execution plan.
In short, keeping vectors and SQL together reduces travel, reduces work, and reduces waiting. Less “fetch and stitch,” more “query and decide.”
Better governance
Section titled “Better governance”Governance is a way of saying: can we trust this system, prove what happened, and control who can do what? In regulated industries such as banks, insurance, healthcare, telecom, and government, we don’t just need answers—we need explainable and provable answers.
That’s why they care about the following:
- Clear lineage: Lineage explains the source of a result. Which tables, which rows, which transformations, and which embeddings were used to derive the answer? Lineage is the ability to trace an output back to its source, almost like a receipt for data.
- Audit trails: An audit trail is a log that records who queried what, who changed what, when, and from where. This matters when regulators ask questions or when something goes wrong, and accountability is needed.
- Reproducible results: When we rerun the same query with the same data, we should get the same result. That’s crucial for compliance, investigations, and fairness reviews.
- Controlled access: Not everyone should see everything. Business systems need fine-grained control, sometimes down to specific rows and columns, so users only see what they’re allowed to see.
And here’s the simple truth: a single database is inherently easier to govern because we are dealing with one place for permissions, logs, policies, backups, data retention, and compliance reviews.
When embeddings live outside the database, governance becomes a two-world problem: two sets of policies, two audit trails, and two chances to miss something.

Figure 17.1: The advantages of integrating AI vectors and SQL
Figure 17.1 summarizes why AI vectors and SQL should be managed in the same platform if at all possible: better locality, consistency, governance, and performance. Vectors inside PostgreSQL aren’t a passing trend. We have seen it with GIS and JSON data, and with full-text search; PostgreSQL’s inherent extensibility absorbs new capabilities and provides a consistent, reliable data management environment.
Designing high-performance hybrid queries
Section titled “Designing high-performance hybrid queries”Now that we have established the need to manage AI vectors and SQL in the same environment, let’s get into the engine room and figure out how to make these multi-modal hybrid queries and transactions fast and practical.
A hybrid query is simply a statement that does the following:
- Uses vectors to find things that are similar in meaning
- Uses SQL to make sure the results are valid in the real world (price, stock, category, region, andpermissions)
This is just like what we saw in Chapter 14, Analyzing Text Documents in PostgreSQL, where we combined text-search vectors with conventional SQL queries.
The best-performing AI and SQL hybrid queries usually follow the same recipe:
- Constrain the dataset with SQL filters: First, shrink the search space with simple rules: “Only Electronics,” “Only current price under $500,” “Only in stock,” and “Only my region.” This is cheap and fast, like narrowing down the search to one shopping aisle before you start comparing products.
- Rank the surviving rows with vector similarity: Now that the list is smaller, use vectors to rank what’s left by closest meaning. This is the expensive part, so you want to do it on fewer items.
- Optionally blend SQL and vector metrics into a final score: Sometimes, “most similar” isn’t enough. We might want results that are also cheaper, more popular, newer, or higher rated. To achieve this, we create a combined score: 70% similarity + 30% business value.
- Return ranked results: Finally, return the top results, optionally including details such as distance score, price, category, and why it matched. That metadata helps debugging, tuning, and allows the user to trust the results.
This pattern sounds simple, but doing it well depends on understanding how PostgreSQL actually runs a query behind the scenes, because the order of operations matters. If we accidentally make PostgreSQL compute vector distances for everything before filtering, the query may slow down significantly. But if we filter first and rank second, performance stays smooth—even at scale.
A good hybrid query may feel like magic to the user, but creating it is basic engineering—careful, ordered, and efficient.
Principle 1: Filter early, rank later
Section titled “Principle 1: Filter early, rank later”Vector search is powerful, but it’s also heavy work for the computer. Vector search means the database is doing math to measure how similar each row is to the query, and each row and the query can consist of up to 4,000 numbers! If we make it do that math on an unconstrained set of data, it’s like asking someone to compare your face to every person in the city before deciding who looks similar.
SQL filters, on the other hand, are cheaper and faster, especially when they can leverage indexes. They’re like saying, “Only look at people in this neighborhood first.” That’s why it’s highly advisable to filter early and rank later.
In the following examples, the positional parameter, $1, represents the embedding of the query text.
Here is an illustration of the good pattern, where we filter first:
SELECT *FROM productsWHERE category = 'Electronics'ORDER BY embedding <-> $1LIMIT 20;This is what happens here:
- First, SQL applies the
Electronicsfilter and reduces the possible result set. - Then, vector similarity is calculated only for those rows.
- Then, we limit the result set to the top 20.
This means that the computationally intensive vector comparison and distance calculation are performed on a much smaller dataset (see Chapter 7, Designing for High - Transaction Volumes and Writing Efficient Transactional Code, for details on the order of processing of the building blocks of an SQL query).
This is an example of a bad pattern, where we rank everything:
SELECT *FROM productsORDER BY embedding <-> $1LIMIT 20;This may look innocent, but it is costly:
- Postgres must calculate the distance (i.e., similarity to $1 for every product)
- All products will then be sorted by the distance metric that we just calculated
- Only after doing all that work can it select the top 20
This process will become extremely slow as the table grows.
A simple analogy explains the difference between the two approaches:
- Good query: “First go to the Electronics aisle, then find the 20 most similar items”
- Bad query: “Scan the entire store, calculate similarity for every item, then pick 20”
That’s why it matters to filter early and rank later to keep hybrid searches fast, scalable, and affordable.
Principle 2: Let each index do its job
Section titled “Principle 2: Let each index do its job”Database indexes are like the table of contents in a book:
- Without a table of contents, the reader must flip through every page to find what they’re looking for
- With a table of contents, they can jump straight to the right section, minimizing search time
In hybrid searches that involve SQL and vectors, we are asking two different kinds of questions:
- Structured questions (fast yes/no rules), such as
category = Electronics, price<500, current = true - Meaning questions (similarity), such as “Find similar products”
PostgreSQL excels at both—but it uses different indexes for each:
- B-tree/BRIN index for structured filters, such as “Find everything in the electronics aisle.” This is quick because the B-tree and BRIN indexes are designed for exact matches and ranges.
- IVFFlat or HNSW index for vector similarity, such as “Within that aisle, find items that are like a Sonos portable speaker.” This index is designed for fast nearest neighbor searches in vector space.
Here are some examples:
CREATE INDEXidx_products_categoryON products(category);defines a B-tree index (the default index in PostgreSQL) on thecategorycolumn of theproductstableCREATE INDEXidx_products_embeddingON products USINGivfflat(embedding vector_l2_ops) WITH (lists = 200);creates an IVFFlat index on theembeddingcolumn for theproductstable, optimizes that for L2 (Euclidean distance) searches, and provides 200 buckets to group items
The PostgreSQL query planner uses them together when the query shape allows it:
idx_products_categorycan help prune the data set and narrow results to the correct category (like walking straight to the Electronics aisle)idx_products_embeddingis used to rank candidates to quickly find the closest matches within that smaller set over the remaining rows (like comparing similar items only in that aisle —not the whole store)
The result combines both speed and relevance:
- Speed because we don’t blindly search the entire table
- Relevance because we use semantic similarity to rank what matters
In short, don’t make one index do two jobs. Let SQL indexes handle the yes/no rules and focus vector indexes on the meaning.
Principle 3: Use JOIN to build multi-table intelligence
Section titled “Principle 3: Use JOIN to build multi-table intelligence”The JOIN operator is the database’s way of connecting related information that is stored in different tables. Here is an example:
- One table has products (name, description, embedding)
- Another table has inventory (stock levels)
- Another table has users (their preferences, location, membership tier)
A real answer usually needs pieces from all of them, and that’s where we use joins.
Example 1
Section titled “Example 1”In this example, we want similar products, but only if they’re in stock and available for sale (“Show me products similar to this … but only the ones in stock”):
SELECT p.product_id, p.name, inv.stock_level, p.embedding <-> $1 AS distanceFROM products pJOIN inventory inv ON inv.product_id = p.product_idWHERE inv.stock_level > 0ORDER BY distanceLIMIT 10;The preceding SQL does three things:
- Finds products that are “close in meaning” (vector similarity)
- Checks inventory to keep only items that are in stock
- Returns the best matches you are available for purchase
For details on the order of execution of SQL, see Chapter 7, Designing for High - Transaction Volumes and Writing Efficient Transactional Code.
Combining the results from both searches in PostgreSQL is easy and returns a useful result. This breaks when both tables are stored in different systems. If embeddings live in a separate vector database, the application code must implement the following awkward steps:
- Ask the vector database for “top similar products.”
- Take those IDs back to PostgreSQL.
- Join them with the available inventory using a custom-coded hash join or merge join.
- If too many items are out of stock, go back to the vector database to fetch more possible choices.
This approach is slower, messier, and harder to keep consistent. When AI vectors live inside PostgreSQL together with the rest of the data on products, prices, inventories, and transactions, it’s one query, one plan, one truth.
Example 2
Section titled “Example 2”This example requires personalization—match products to a user’s taste. A personalization query could ask “Select products that match this user’s preferences” (u.preference _vec in the following hypothetical query):
SELECT p.product_id, p.name, p.embedding <-> u.preference_vec AS distanceFROM users uJOIN products p ON TRUEWHERE u.user_id = 42ORDER BY distanceLIMIT 15;Let’s reword this in plain English:
- The user has a preference vector:
u.preference_vec(their taste fingerprint) - Each product has an embedding vector:
p.embedding(its characteristic fingerprint)
The database compares them and returns the closest matches. This is the core pattern behind personalization systems: “People like you also liked…” or “Recommended for you…”. You can easily combine these with further joins to limit by target price, inventory availability, and so on.
In short, joins are how you turn vector similarity into real-world intelligence, because the final answer almost always depends on more than similarity. It also needs to consider other hard facts, such as inventory, price, region, eligibility, compliance, and user context.
Principle 4: Use hybrid scoring models
Section titled “Principle 4: Use hybrid scoring models”Sometimes “most similar” is not the same as “best.” A vector search can tell you which items are closest in meaning to your query. But in real applications, you also care about business signals such as popularity, price, margin, ratings, freshness (newer items), risk, and compliance flags.
A hybrid scoring model is simply a way to blend multiple AI-driven similarity calculations with other SQL-driven ratings into one final ranking score.
Think of it like judging a contest with multiple criteria:
- 60%: How well does it match what the user means?
- 40%: How profitable is it for the business?
The following hypothetical query illustrates how multiple scoring models could be combined:
SELECT p.product_id, p.name, (0.6 * (1 - (p.embedding <-> $1))) + (0.4 * p.margin_score) AS final_scoreFROM products pWHERE p.category = 'Swimwear'ORDER BY final_score DESCLIMIT 10;The preceding SQL does the following:
- It finds swimwear that is similar to what was asked for.
- It also boosts high-margin clothes.
- Then, it combines both into one number called
final_score. - Finally, it sorts by that score and returns the top 10.
The results aren’t just “closest match,” they’re “closest match and most likely to be a profitable recommendation.”
This method lets you incorporate both of the following:
- Semantic closeness (vector similarity: what feels like a match)
- Business relevance (SQL-derived signals: what’s trusted, valuable, or profitable)
And this idea applies far beyond retail:
- Repair suggestions: Similar issue + higher risk first
- Insurance claims: Similar claim + higher fraud risk first
- Routes: Similar destination + lower cost + higher safety
Postgres provides an elegant solution because it can compute similarity, apply rules, combine scores, and return ranked results—all in a single query and engine.
Principle 5: Push computation into the database
Section titled “Principle 5: Push computation into the database”All too often, data is moved to the application, and that’s where many calculations happen. We encourage developers to think differently: don’t make the application do the database’s job. Push many calculations into the database close to the data, especially those where the planner can leverage statistics to create an optimal plan that minimizes I/O and CPU.
A common mistake (the anti-pattern) looks like this:
- Do the “similarity search” in a separate vector database.
- Pull back the top results (IDs) into your app.
- Apply business rules in code (price, stock, region, and category).
- Fetch more details from your main relational database.
- Re-rank everything again in the app.
This approach works, but it is very inefficient and very costly. It causes the following:
- Higher latency: The data is bouncing across systems: app to vector DB -> app -> Postgres -> app. Every hop adds time.
- Inconsistency: The vector DB and the relational DB can get out of sync. You might recommend something that’s out of stock or not accessible to that user.
- Code complexity: Your application becomes a mini query engine, handling filtering, joining, ranking, and retrying. That logic is duplicated across services, making testing difficult.
- Operational overhead: You are running and monitoring two databases and their synchronization pipelines. More building blocks mean more things that can go wrong.
The correct pattern is to do it in a single SQL query in PostgreSQL.
In that pattern, the following occurs:
- SQL handles the strict rules (category, current price, stock, region, and permissions)
- AI vectors handle similarity ranking
- PostgreSQL handles joins and scoring
- The database returns the final ranked results
Why is this pattern preferable?
- The planner and optimizer do the work: PostgreSQL uses its statistics and planning engine to create the most efficient plan, which includes which indexes to use, which filters to apply first, and how to join tables.
- The database provides ACID transactional guarantees: Results are consistent with the current state of the database—no stale embeddings or outdated prices.
- The architecture becomes healthier: We have fewer moving parts and fewer custom integrations with disparate processes. This comes with less operational burden and much easier governance.

Figure 17.2: Five principles of the design pattern for high-performance hybrid queries
Figure 17.2 summarizes the five design patterns for high-performance hybrid queries:
- Filter early, rank later.
- Let each index do its job.
- Use joins to build multi-table intelligence.
- Use hybrid scoring models.
- Push computation into the database.
In short: one engine, one query, one truth. Let the app ask the questions, let PostgreSQL do the heavy data lifting, and get the answers.
Real-world examples and patterns
Section titled “Real-world examples and patterns”So far, we’ve talked about how things should be done. Now, let’s look at the corresponding code for a few examples: retail fraud detection, maintenance log analysis, and customer churn prediction in telecom.
Retail: Semantic search and inventory constraints
Section titled “Retail: Semantic search and inventory constraints”In real use cases, people don’t ask “Show me similar items” and stop there. They ask for items that are similar and also meet real-life constraints, such as size, price, and availability. These are patterns you’ll see everywhere, not just in retail.
For example, a user says, ” Show me workout shoes similar to this, in my size, under $150.”
This hypothetical query does exactly that:
SELECT name, price, size, stock_count, description_vec <-> $1 AS distanceFROM shoesWHERE size = 11 AND price < 150 AND stock_count > 0ORDER BY distanceLIMIT 12;Let’s review every single clause in the query:
description_vec<->$1: This is the “meaning match” part. It compares the user’s shoe description (turned into a vector) with each shoe’s description vector and measures how similar they are.WHERE size = 42: Only show shoes in the user’s size. No useless results.AND price<150: Only show shoes within budget.ANDstock_count>0: Only show shoes that are available to purchase right now.ORDER BY distance: Put the most similar shoes first.LIMIT 12: Return only the top 12 results—like a clean search page.
This is powerful because the output is ready for immediate use by the application. There is no need to fetch results and then filter them in application code. The database already returns the right answers—quickly and cleanly.
In other words, vectors find the “right vibe.” SQL ensures it fits the “real-world rules.”
Banking: Fraud case similarity
Section titled “Banking: Fraud case similarity”Fraud detection and analysis is one of the major application areas for machine learning and AI. In banking, investigators often want to answer a question such as, “Have we seen fraud cases like this one before?”
The “like this one” part is messy because fraud notes are written in natural language. Two cases can describe the same pattern using totally different words. That’s where vectors help.
Here is a hypothetical query that compares the embedding of the current fraud case (represented as $1) to known fraud cases and their embeddings:
SELECT case_id, amount, region_code, notes_vec <-> $1 AS distanceFROM fraud_casesWHERE amount > 10000 AND status = 'OPEN' AND region_code = 'W1'ORDER BY similarity ASCLIMIT 20;Let’s review the clauses in the query:
notes_vec<->$1 ASdistance: This compares the meaning of the current case notes (the vector,$1) with the embeddings of past case notes stored as vectors. It finds cases that sound different but mean the same thing and are semantically close to each other, that is, have a small Euclidean distance (<->).WHERE amount>10000: Only look at high-value cases (because the stakes are higher).AND status = 'OPEN': Only show cases that are still active and need attention.ANDregion_code= 'W1': Only include cases from a specific region (maybe due to local rules or investigation scope).ORDER BYdistance ASCLIMIT20;: Show the 20 most similar cases first.
This is semantic closeness plus strict rules in one place:
- Vectors help investigators find patterns quickly
- SQL ensures that the results comply with operational and regulatory constraints (region, status, thresholds)
This is not just about finding similar cases; it is about finding relevant, actionable ones.
Manufacturing: Maintenance log analysis
Section titled “Manufacturing: Maintenance log analysis”Maintenance logs combine IoT data, such as temperature, vibrations, hours of operation, rotation speed, and so on, and text entered by technicians during installation, maintenance, and repair. Two technicians may describe the same problem using completely different words.
In manufacturing, we often receive requests to find similar problems and identify successful solutions—for example, “We’re seeing this failure right now. Have we seen something similar before, and what fixed it?”
AI vectors will help us handle manual text entry and match data patterns.
This hypothetical query goes one step further—it also prefers recent logs, because a fix from last week is often more relevant than one from five years ago:
SELECT log_id, event_timestamp, (0.7 * (1 - (log_vec <-> $1))) + (0.3 * freshness_score(event_timestamp)) AS scoreFROM maintenance_logsWHERE equipment_type = 'AXLE'ORDER BY score DESCLIMIT 5;Let’s review the details of the query:
WHEREequipment_type= 'AXLE': Only look at logs for the same kind of equipment. An axle problem shouldn’t be compared to a cooling fan problem.(1 - (``log_vec<->$1)): This is the “similarity” part. The database compares the meaning of the current failure report ($1) to each log’s vector. More similar equals a higher score.freshness_score(``event_timestamp``): This gives extra points to newer logs. It’s a “recency boost.”0.7 * similarity + 0.3 * freshness: This creates one combined score—70% based on similarity and 30% based on recent events.ORDER BY score DESC LIMIT 5: Return the top five most useful matches, similar and recent.
The combination of semantic search with SQL data helped us find reports that pertain to the specific part, are described similarly by the technicians, and are recent and likely relevant.
Telecom: Customer churn analysis
Section titled “Telecom: Customer churn analysis”Customer churn, meaning customers who cancel their contract and sign up with a different provider, is a key metric in subscription businesses. Wireless phone services are highly competitive, and a common business question is, “Which customers look like this profile… and are at risk of leaving?”
This hypothetical query does exactly that using vectors for similarity and SQL for business action:
SELECT c.customer_id, c.behavior_vec <-> $1 AS sim, churn_probabilityFROM customers cWHERE plan_type = 'PREMIUM'ORDER BY sim, churn_probability DESCLIMIT 10;Let’s analyze the building blocks of the query:
c.behavior_vec<->$1 AS sim: Each customer has a “behavior vector” that represents patterns such as usage, complaints, payments, app activity, and so on.$1is the vector for the kind of customer profile you’re interested in. The database compares them and finds customers whose behavior is most similar.churn_probability: This has been defined elsewhere based on recent usage trends, late payments, and complaint behavior.WHEREplan_type= 'PREMIUM': Only look at Premium customers (maybe because you’re running a retention campaign for them).ORDER BY sim, ``churn_probabilityDESC: First, it shows the customers most like the profile. Among those, it puts the ones with higher “churn probability” (more likely to leave) at the top, so you can act where it matters most.LIMIT 10: Return the top 10 targets.
This is powerful as it’s not just analytics. It’s direct input into decision-making:
- Vectors answer “Who else behaves like this?”
- SQL adds “Only Premium.”
- The churn score adds “Who needs attention first?”
That’s AI and SQL in one flow, one query that directly produces an actionable shortlist for retention offers, outreach, or service improvements.
Architecture: Why this matters
Section titled “Architecture: Why this matters”In the previous sections, we reviewed the five principles for high-performance hybrid queries and examined a few query examples from retail, manufacturing, banking, and telecom. However, solving this problem (or avoiding it) is not just about writing better queries; it’s about building systems that don’t crumble when real traffic, real data, and real deadlines show up.
Simpler systems scale better
Section titled “Simpler systems scale better”When we keep everything in one system (PostgreSQL handling both SQL and vectors), life gets easier in very practical ways:
- Easier to deploy: We use a single database platform, not two. Fewer moving parts means fewer “it worked in staging but broke in prod” surprises.
- Easier to secure: One place to manage users, roles, permissions, and access rules. No need to duplicate policies across a vector store and a relational database and hope they stay consistent.
- Easier to monitor: One set of dashboards, logs, alerts, and performance tuning tools. When something is slow, you can find the cause faster instead of playing “blame ping-pong” between systems.
- Fewer points of failure: Every extra system adds another place things can break: network links, sync pipelines, auth, upgrades, backups. One system reduces the failure surface area, thereby improving reliability.
- Less custom code: All the queries run in one database; there is no need to develop custom code that merges the results from different databases. There are also no data pipelines to synchronize multiple source systems.
In short, simple architectures scale better because they have fewer moving parts.
Unified governance
Section titled “Unified governance”Governance is a critical topic in AI solutions. Governance boils down to simple questions: can we prove what happened, control who can see what, and stay compliant?
When your data and embeddings live in one database, governance becomes much simpler because there’s only one place to manage and verify.
That’s why auditors love simple architectures:
- One logging system: There’s a single record of activity—who queried what, who changed what, and when it happened. There is no need to stitch together logs from multiple systems and guess the whole story.
- One policy engine: All rules (permissions, row-level security, and retention policies) are defined and enforced in one place. You’re not trying to keep two different systems aligned.
- One access mechanism: Users authenticate once, roles are managed once, and access is granted once. No “they have access here but not there” confusion.
Risk teams love systems that don’t proliferate because every extra system adds another set of credentials, another place data might leak, another audit scope, and another upgrade or misconfiguration risk.
One system is easier to trust, easier to control, and easier to prove compliant.
PostgreSQL’s relational model remains future-proof
Section titled “PostgreSQL’s relational model remains future-proof”The reason PostgreSQL is still thriving after decades traces back to the initial design decisions taken by Michael Stonebraker and team over 30 years ago: the object-relational model and its inherent extensibility have enabled PostgreSQL to remain relevant by adding new capabilities without sacrificing its core strengths: reliability, consistency, security, and SQL.
Over the years, with a combination of core technology and extensions, PostgreSQL has integrated major new styles of data and workloads, such as the following:
- JSON(B) for storing and handling flexible, semi-structured data without needing a whole new database
- Full-text search can search documents and descriptions directly in the database
- Time-series handles sensor data, metrics, and event streams naturally
- Columnar storage enables faster analytics queries on large datasets
- Logical replication safely and efficiently copies and synchronizes data across systems
- Distributed clusters that scale out for high availability and global workloads
- AI vectors work with meaning and similarity—powering AI search and retrieval in the same place as operational data
Behind all of that lies a simple idea: the future favors architectures that integrate, not designs that fragment. Generally, integrated solutions tend to be more effective and efficient than best-of-breed, custom-integrated architectures, as the ensuing fragmentation challenges often outweigh the local efficiency gains.
In simple terms, tools that keep everything connected and consistent will win because they reduce complexity. Tools that force you to stitch together multiple technology platforms to answer a single question will keep driving up costs, risks, and delays.
Summary
Section titled “Summary”This chapter demonstrated that combining vectors and SQL inside PostgreSQL is not only possible—it is strategically advantageous.
Vectors bring meaning. SQL brings structure. Together, they enable multi-modal reasoning.
We explored how hybrid queries allow applications to think semantically while respecting the business logic encoded in relational models. We studied indexing, filtering strategies, hybrid ranking, vector joins, and real-world patterns across retail, finance, telecom, and manufacturing.
The message is simple: AI doesn’t eliminate the need for SQL. AI makes SQL more important. And SQL makes AI truly usable. With pgvector and PostgreSQL, you get a single, unified engine that can retrieve, reason, filter, rank, and decide—all within the comfort and stability of a trusted relational platform. This fusion marks a new chapter in database evolution: a database that not only stores data but also understands it.
The next chapter teaches us how to generate embeddings for datasets and queries by connecting PostgreSQL to hosted LLMs and how to store the resulting vectors in PostgreSQL.