Tying it All Together
local graph
Chapter 21 — Tying it All Together
Section titled “Chapter 21 — Tying it All Together”Tying It All Together
Section titled “Tying It All Together”In this book, we have shown how to use PostgreSQL to create modern enterprise solutions that incorporate transactional, analytical, and AI capabilities. The key lessons learned are as follows:
- Leverage PostgreSQL and its ecosystem to organize and manage polymorphic data (numbers, characters, JSON documents, AI embeddings, GIS data, and custom data types) to handle polymorphic data reliably and effectively.
- Keep different data formats and their operators, such as text searches, JSON transactions, or vector-based similarity searches, under one ACID-compliant transactional umbrella to minimize integration headaches, architectural fragility, network delays, and operational challenges.
- PostgreSQL is more than the standard PostgreSQL distribution that you may download from PostgreSQL.org. It has a vast ecosystem of extensions, such as
pgvectorfor AI embeddings and approximate nearest neighbour AI computations,pg_backgroundfor asynchronous background processing, andplpgsql_checkto check database procedures. Leverage these to achieve the full power of PostgreSQL. - When creating large-scale hybrid data-intensive enterprise applications, build on PostgreSQL’s native data replication to create easy-to-manage and effective data architectures that leverage the principle of replicating reference data, distributing transactions, and integrating data for analytics and AI.
- Take advantage of these same capabilities to create modular data services optimized for transactional, analytical, and AI workloads through targeted, workload-specific data models, index strategies, and effective noisy-neighbor-avoidance strategies.
Figure 21.1 highlights the modular data services, all built in PostgreSQL, but specialized for their workload by using different modeling approaches and leveraging PostgreSQL’s extensible data types, operators, and indexes:

Figure 21.1: Data services with their data modeling specialization
PostgreSQL capabilities
Section titled “PostgreSQL capabilities”In this book, we went beyond standard SQL and introduced many architectural and data modeling concepts that we believe are key to creating high-performance enterprise solutions. The right architecture provides a solid foundation for a scalable system, and the right data model helps developers avoid many future performance and manageability issues.
Architectural concepts: Polymorphic, versatile, hybrid
Section titled “Architectural concepts: Polymorphic, versatile, hybrid”Traditionally, databases were seen as monoliths and specialists. Specialty databases were used for specific data formats; JSON documents, key-value pairs, text search, and AI vectors each had their own specialized database software. Similarly, analytical and transactional use cases were implemented in database products tailored to them.
In this book, we show that one database system – PostgreSQL – can store conventional SQL data alongside JSON, KVP, GIS, text, and AI vectors in the same database, and process transactions under the same ACID umbrella, using the same query language and the same programming language. We refer to this as PostgreSQL’s polymorphism.
Different use cases need different architectures, but they can all be built on Postgres, and within a use case, a single PostgreSQL database can handle multiple data formats. Thus, we see transactional databases built on PostgreSQL adopt highly normalized data models. Analytical applications thrive with star schemas, and AI applications successfully adopt AI embeddings alongside standard SQL data. This reflects PostgreSQL’s versatility.
Hybrid processing, where SQL-based queries provide hard and fast yes/no decisions, in combination with AI-based approximate nearest neighbor calculations that result in soft sliding scales, is a natural extension of PostgreSQL’s capabilities.
This teaches us that use-case-specific data services can be polymorphic and integrate hybrid processing, but each use case benefits from an optimized data model, and because it has different resource consumption and transactional patterns, it should be isolated from other services to avoid the noisy neighbor (or resource hog) problem. PostgreSQL provides several capabilities to achieve this, such as:
- Logical replication with row-based and column-based filtering helps us create modular data services. These modules can be geo-distributed, partitioned to scale with the business needs, and optimized for the use case (Chapter 11*,* Feeding the PostgreSQL Data Warehouse).
- PostgreSQL provides a wide range of procedural languages, ranging from PL/PGSQL – the native procedural language – to PL/Python, and includes PL/TCL, PL/Perl, PL/R, and many others. This allows us to create rich logic that operates right next to the data, avoiding network latency, and embeds business logic within the ACID transactional model (Chapter 6*,* Functions and Stored Procedures).
- SQL views, materialized views, and triggers are a rich set of tools to transform data. Combined with logical replication, we can keep a transactional representation of the data in sync with an analytical or AI-focused data model – without using any third-party tools, and without leaving the realm of PostgreSQL. The same skills, the same license, the same operational model! (Chapter 12, Transforming the Data for Analytics; Chapter 18, Step-by-Step Approach to Integrating LLMs with PostgreSQL to Create Complete AI Applications and Chapter 19, Production-Ready AI Embedding Pipeline Patterns.)
- Data pipelines, asynchronous transport, and transformation mechanisms are used to decouple distributed systems and isolate them from network effects, transient slowdowns, and temporary outages. A combination of triggers, tables, and workers can be used in PostgreSQL to create robust data pipelines that communicate with non-PostgreSQL systems, such as cloud-based LLMs (Chapter 18, Step-by-Step Approach to Integrating LLMs with PostgreSQL to Create Complete AI Applications and Chapter 19, Production-Ready AI Embedding Pipeline Patterns).
- Polymorphic and hybrid processing: SQL logic, hard and unequivocal, combined with ANN calculations that generate meaning on a sliding scale, are the foundation for implementing generative AI solutions in PostgreSQL (Chapter 19, Production-Ready AI Embedding Pipeline Patterns).
- Agentic AI creates multi-component systems that combine AI agents with other systems that act upon the AI’s output, a.k.a. actuators. The Model Context Protocol (MCP) provides a secure, auditable framework that enables PostgreSQL to act as both the AI agent that generates recommendations and the tool that executes them (Chapter 20, PostgreSQL and MCP*:*The Blueprint for a Robust AI Assistant).
Data management concepts
Section titled “Data management concepts”PostgreSQL traditionally thrived in transactional applications, where normalized data models are preferred. In this book, we show that PostgreSQL is fully capable of supporting analytics models, such as star schemas, and AI models, such as vector-based embeddings.
- ACID are key to transactional databases. Whereas most developers may believe that ACID transactions are rigid and inflexible, and that they succeed or fail, we show in Chapter 5 that PostgreSQL allows developers to influence isolation levels and control transaction flows.
- Normalized data models are key to transactional performance. Chapter 5, Transactions, ACID Compliance, and Data Normalization teaches the developer, step by step, how to proceed from 0NF to 3NF.
- Data types, operators, and indexes are key to every database. Choosing the optimal data type is key for any database use case. The golden rule advises selecting a data type that accurately represents the domain, supports the appropriate operators, and comfortably accommodates the expected data range. Chapter 7, Designing for High-Transaction Volumes and Writing Efficient Transactional Code details the data types and selection criteria for SQL.
- Analytical data models have different requirements; for example, they focus on selecting, grouping, aggregating, and analyzing large datasets. Chapter 10, The Analytics Data Model provides an overview of data vaults and details how to implement star schemas in PostgreSQL.
- AI models, focused on approximate nearest-neighbor calculations to support semantics and meaning, leverage embeddings often derived from SQL data. AI vectors and indexes are discussed in Chapter 15, Database Requirements for Artificial Intelligence Use Cases.
Key PostgreSQL 18 innovations
Section titled “Key PostgreSQL 18 innovations”PostgreSQL 18, released on September 25, 2025, was a major step forward for the open source database community. Many of the enhancements focus on performance, security, and internal improvements (OAuth 2.0 authentication, FIPS mode validation, deprecation of MD5 authentication, parallel application of logical replication transactions, and asynchronous IO) and did not fall within the scope of the book.
We were able to illustrate the following features in this book:
- Temporal constraints that control date and time range overlaps
OLD/NEWvalues in theRETURNINGclause forINSERT,UPDATE,DELETE, andMERGEcommands allow tracking and reasoning about before/after values for transactions.UUIDV7is a time-ordered Universally Unique Identifier that reduces index fragmentation and tends to improve retrieval in sequential read operationspg_stat_statementsvisibility for parallelism – in our query statistics, we show how newer instrumentation helps you reason about planned versus realized parallel execution, which matters when diagnosing “why did this query stop scaling?”- The
casefold(``)function, often used in the context of theLIKEstatement, provides a global, Unicode-compatible way to work with strings independently of uppercase/lowercase.
PostgreSQL 18 contains additional innovations worth noting, even though we do not cover them in this book:
- Virtual generated columns compute values at query time and can simplify schemas when a derived value is primarily read-facing
- Skip scan for multicolumn B-tree indexes can improve index usage for certain query patterns and reduce unnecessary scans
PG_UNICODE_FASTcollation and nondeterministicLIKEsupport broaden Unicode-correct string comparison and pattern matching behavior across languages- Upgrade improvements, including preserved planner statistics and
pg_upgradeenhancements, reduce the “post-upgrade performance dip” and speed up major version transitions - Page checksums are enabled by default in i
nitdb, strengthening baseline corruption detection in newly initialized clusters
PostgreSQL and the AI revolution
Section titled “PostgreSQL and the AI revolution”PostgreSQL has won the hearts and minds of developers of transactional applications and has made great inroads into the analytics space. A similar trend is happening in AI. While initial developments relied on specialized data platforms such as Pinecone or Weaviate, with the rise of generative AI, the pgvector extension has become the standard for storing vector embeddings in Retrieval-Augmented Generation (RAG) apps. This trend is driven by developers who didn’t want to spin up a new niche database just for vectors; they just installed an extension on their existing Postgres. Operational simplification and streamlined license models also contributed to this development.
RAG made vectors famous by solving a very specific problem: “Find relevant text chunks, then let the model answer.” That is powerful, but it is mostly document-first; your evidence consists of paragraphs and passages. The moment your questions involve prices, current offers, validity windows, inventory rules, customer entitlements, or compliance boundaries, documents become a weak substrate. Relational data is different: it is shaped by constraints, keys, and governance. When you bring embeddings into PostgreSQL, you don’t just retrieve “similar text.” You retrieve structured truth, rows that already live inside the rules of your system.
In Chapter 18, Step-by-Step Approach to Integrating LLMs with PostgreSQL to Create Complete AI Applications and Chapter 19, Production-Ready AI Embedding Pipeline Patterns, we described how PostgreSQL, together with pgvector, is used to develop a generative AI application that integrates LLM capabilities to transform SQL query output into natural language. This chatbot is a first step towards reducing the gap between the database and the human user.
This is an important shift: the assistant isn’t answering from scraped text or loosely governed documents. It is answering from SQL result sets. That means the system can enforce limits, join rules, and business constraints, then the model’s job becomes what it should be: a translator and explainer, not an inventor. In other words, the database has the authority; the model becomes the narrator.
Chapter 20, PostgreSQL and MCP:The Blueprint for a Robust AI Assistant showed how we can take the next step by using AI to make it easier for users to ask questions. Instead of mandating SQL for querying the database, we showed how users can query it in natural language. The chatbot uses an LLM to generate SQL, checks the generated SQL for safety, runs the query, and then uses another LLM to transform the output into natural language.
At this point, a reader might reasonably ask: “Isn’t this already a tool-using assistant? What does the MCP really add?” The answer is: what we built is a pattern; the MCP is the standard contract that makes that pattern safe to scale across tools, teams, and systems. Our “governed query assistant” validates SQL and returns evidence rows, which is great, but the contract between the model and the tool is still largely implicit, embedded in prompts and function logic. The MCP turns that implicit contract into an explicit one: the model requests an action using a defined tool schema; the system enforces policy, executes under the right identity, and returns typed results with audit metadata. That difference becomes decisive the moment you add more tools, more datasets, more roles, and more production pressure.
The underlying integration of SQL and meaning is foundational. Whereas early AI applications, mostly focused on generative AI and chatbots, worked on unstructured text and documents, the perspective of working with data stored in relational databases will help AI projects overcome some of their biggest hurdles:
- Data quality: Text and document data, especially data scraped from websites or internal document repositories, tends to be of lower quality than transactional data managed in relational databases. Relational data has been considered mission-critical for many years, and AI applications leveraging this data tend to have higher reliability. Integrating SQL into the queries also provides some hard boundaries, further reducing the chance of hallucinations.
- Data governance: Relational databases have built-in role-based access control (RBAC) and strong governance processes. AI that leverages this data will benefit greatly from that foundation.
A useful way to think about it is “two truths cooperating.” Semantic search gives you recall; it helps you find what feels relevant. SQL gives you precision—it enforces what is allowed, current, valid, and compliant. When these two work together, you get assistants that feel natural to use and trustworthy to operate.
Besides quality and governance advantages, the integration of AI and databases opens up the use of AI and databases for the following:
- Using AI to democratize data access so analysts can ask questions without needing detailed knowledge about the schema or SQL: databases with AI.
- Using data that is stored in relational databases to drive AI for generative AI and more complex agentic AI applications: databases for AI
- Using AI to improve the database itself, for example, by analyzing the database structure for missing indexes or making database tuning recommendations: AI for the database.
The connection of AI capabilities with the traditional properties and processes of enterprise databases opens up whole new possibilities!
So far, we have focused on how AI interacts with the database, but the potential is greater: AI can use information from one database to generate instructions to change another database. For example, intelligent sales analysis indicates that certain prices should be lowered, and AI forwards that instruction to the product pricing database instead of informing an analyst and expecting the analyst to act on the information), or AI detects negative customer sentiment about product A and reduces its reorder volume.
Here’s the turning point: once an AI system can act, not just answer, you need governance that survives success. Prompts are advice. Production needs contracts. You need typed tool inputs, permissioned execution identities, policy enforcement, and audit trails that can tell you who asked what, what tool ran, what data returned, and what happened next. That is exactly the gap the MCP was designed to close.
This is where the MCP steps in (see Chapter 20, PostgreSQL and MCP*:*The Blueprint for a Robust AI Assistant). Instead of having AI agents interact directly with databases and other business systems, the MCP provides a secure, audited interface that controls their actions and coordinates the actions of AI agents and tools.
PostgreSQL: A data platform for the future
Section titled “PostgreSQL: A data platform for the future”PostgreSQL has won the hearts and minds of enterprise developers and has emerged as the #1 database used and loved by developers (see Chapter 1, Transactional, Analytical, and AI Business Systems and Their Database Requirements). For many years, PostgreSQL has been the undisputed choice for transactional applications, but it has historically not been considered for enterprise-level analytics. Its capabilities introduced over the last 10 years (materialized views, CUBE, ROLL UP, GROUP SETS, recursive CTE with cycle detection, BRIN indexes, etc.) make it a serious contender. Important developments in the PostgreSQL ecosystem, such as TimescaleDB (a PostgreSQL extension for high-performance real-time analytics on time-series and event data), WarehousePG (massive parallel processing MPP capable data warehousing solution based on PostgreSQL), pg_lake (integration of Iceberg open data lake with PostgreSQL), ParadeDB (Elastic search with BM25 scoring for PostgreSQL), and pg_duckdb (integrating the DuckDB columnar-vectorized analytics engine into PostgreSQL), are pushing the analytics envelope, allowing applications to “speak Postgres” for ever-larger and more complex analytical workloads.
Similarly, pgvector and recent additions that scale pgvector, such as Scalable Nearest Neighbors (SCANN) and Disk-based Approximate Nearest Neighbors (DiskANN), position PostgreSQL as the leading platform for vector-based AI operations. PostgreSQL’s unique ability to combine AI with SQL makes it a powerful choice for AI solutions.
What makes this combination unusually powerful is not that PostgreSQL can “do vectors.” It’s that PostgreSQL can do vectors + joins + constraints + governance in one place. You can retrieve by meaning, filter by policy, and return evidence rows with lineage—all while keeping the operational model familiar to enterprises. This is how AI moves from experimentation to adoption: not by being clever, but by being governable.
Modern enterprise applications must combine transactional, analytical, and AI capabilities in a near-real-time, scalable, cost-effective, and agile way. PostgreSQL, its ecosystem, and recent innovations in analytics and AI position PostgreSQL as the #1 choice for a future-proof enterprise data platform.
Just use Postgres – get stuff done!