Skip to content
ImagineWorld

The Analytics Data Model

node_idnode-book_ai-ready-postgresql-18_chapter-10-the-analytics-data-model
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleThe Analytics Data Model
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Database transactions focus on executing and recording business activities, such as sales orders, accounts receivable, accounts payable, and bank transfers. These systems operate on small sets of records at a time, apply changes, and persist in ensuring durability and consistency. Their primary goal is to ensure that every update is accurate and timely, and that no anomalies appear when data is inserted, updated, or deleted.

To achieve this reliability, transactional environments rely on highly normalized data models that minimize duplication and maintain strict referential integrity. The structure is optimized for rapid, reliable write operations, supporting predictable behavior even as thousands of small transactions flow through the system each day. Because of this emphasis on operational correctness, transactional models are tightly structured and carefully governed through a normalization process.

Analytical systems work with the same underlying business data but use it in a fundamentally different way. Instead of focusing on individual updates, analytical systems retrieve, group, aggregate, and analyze large volumes of transactional records to uncover patterns and answer business questions. These questions often involve broad time ranges, product lines, or geographic segments, such as What products from The Gap did we sell last week in the Northeast? or Are the sales of The Gap products in the Northeast growing, and if so, where and which specific products drive the growth?

Analytics workflows might require gathering all 2024 purchases of products imported from France, then organizing and aggregating that data to identify trends that help guide strategic decisions. Because these tasks involve scanning and reshaping large datasets rather than updating small ones, analytical environments have very different data modeling needs. Analytical models are intentionally denormalized and leverage focused data duplication to reduce join complexity and improve read performance, enabling faster insights even when working with millions of records.

In this chapter, we will discuss two such analytics models: data vaults and star schemas. Star schemas are popular, straightforward to implement, and provide a solid foundation for high-performance reporting. Data vaults, while more complex to implement and query, are better suited to rapidly changing, fragmented, or otherwise complex data environments that require flexibility and consistency as they evolve.

This chapter covers the following topics:

  • Star s chema s, the most popular way to model data for analytics use cases
  • D ata v ault s, an enterprise-level data modeling technique that handles heterogeneous source systems and makes it easier to manage schema evolution
  • Relational Analytical Processing (ROLAP), an approach in which analytics queries are run directly on the normalized data model

We conclude by comparing the three approaches and providing guidance to developers on when to use each technique.

Analytics systems focus on making it easy to query large amounts of data and provide efficient support for analyzing them. The star schema has become the preferred choice to meet those requirements. Star schemas divide data into two primary components: facts and dimensions. Facts are quantitative measurements, such as sales amounts or quantities purchased. Dimensions provide descriptive context—such as time, location, product, or customer—enabling rich analysis. Facts are at the center of the star, whereas dimensions represent the points of the star (see Figure 10.1).

Figure 10.1: Star schema for sales data

Fact tables store the numerical metrics of business transactions. They usually contain many rows and relatively few columns, representing most of the data in a star schema. Fact tables often use a composite key that consists of the foreign keys from related dimension tables.

Fact tables can be structured in several ways:

  • Transactional facts record detailed events, such as individual sales transactions
  • Pre-computed aggregates, such as the monthly sales by customer
  • Periodic snapshots capture measurements at regular intervals (e.g., daily inventory balances)
  • Accumulating snapshots, which track progress over time, possibly with specific milestones

Dimension tables contain descriptive attributes that define the who, what, where, and when of each fact. They typically have fewer rows than fact tables, but many columns, containing hierarchies for different levels of aggregation. For instance, the product dimension may include the country of origin, brand, category, and other relevant attributes. These hierarchies enable drill-down and roll-up analysis across different granularity levels.

Keep in mind that the content of dimension tables can change, for example, when a customer moves and updates their address. To track those changes over time, we can use s lowly c hanging d imensions (see Chapter 5, Transactions, ACID Compliance, and Data Normalization).

Every dimension table is directly linked to the fact table, making querying straightforward and efficient, as it requires only a single join between each dimension and the fact table.

When designing a star schema, the developer needs to think about the following:

  • What is the level of detail in the table, a.k.a. the data grain? For example, do we record every single sales transaction, or do we store a customer’s cumulative purchases for a given day?
  • If many of our star schemas use the same dimensions, it will become much easier for users to make sense of the data (and the maintenance of the data warehouse becomes a lot easier). Dimensions that are shared across multiple stars are called c onformed d imensions.
  • The same is true for our facts. They should use the same units of measure where possible. For example, using the metric system for all weights and sizes for products, packaging, shipments, and so on is preferable to using metric units for products but imperial units for shipments. In that case, we talk about c onformed f acts.

For most enterprises, the analytics team will define multiple star schemas, as each focuses on responding to a specific set of analytics requests. Expect to see stars for orders, shipments, customers, payments, sales performance, and other business metrics.

To illustrate how to create, manage, and use star schemas, we have developed a sales-focused star schema (see Figure 10.1), utilizing the dataset from Chapters 4 – 8. This star schema enables the analysis of sales (the facts) over time, by location, customer, and product (the dimensions). Each dimension features one or more hierarchies. Notably, the geography dimension also includes sales region information.

This star schema will make it easy to answer questions such as How many shirts that were made by a German company did we sell in each state in each quarter of 2024? While those questions could have been answered based on the normalized transactional schema, the query would have been exceedingly complex due to the large number of tables to join, and performance would not have been satisfactory.

Star schemas are not the same as data marts. A data mart is a subject-oriented subset of a larger data warehouse, designed for a specific business function or team. A star schema is a data modeling technique used to organize data within a data mart or a data warehouse.

Star schemas provide a foundation for analytics queries. We will leverage them to illustrate PostgreSQL’s native analytics capabilities:

  • Views
  • Materialized views
  • Groups
  • Grouping sets
  • Rollups
  • Window functions
  • Common Table Expression s (CTE s)

Views encapsulate complex queries, give them a name, and store the SQL definition (not the results) in the database. Views simplify the code, eliminate redundant query text, and make it easy to share standardized requests among multiple users. Views are generated when accessed, ensuring they are always up to date; however, this process can be resource-intensive and slow performance.

Materialized v iews encapsulate queries, just like views, and allow us to precompute aggregate data, for example, daily sales by region. They can also be used to represent dimensions; for example, the product dimension, with its hierarchies, could be a table or a view. While views are generated when accessed, materialized views are populated at creation time and can be indexed, making them significantly faster and more efficient. However, they require periodic updates to remain current as PostgreSQL does not yet provide self-refreshing materialized views; otherwise, they become stale and diverge from the transactional data, making queries less reliable.

Groups are the foundation for aggregating data. They allow specifying aggregates, such as SUM or AVG, for a group of data defined by values in one or several columns (e.g., brand or country of origin).

Grouping s ets allow the creation of multiple groups and provide subtotals for each group. For example, a grouping set of country of origin, brand, and category, and another one for origin and brand, a third one only for brand, and an empty one (i.e., refers to all the data) will calculate a hierarchy of subtotals at each level: all the data, a subtotal for each brand, a subtotal for each combination of country and brand, and a detailed one for each permutation of country, brand, and category.

Rollups take the concept of groups to the next level. Instead of specifying the levels of the hierarchy, they create the levels automatically from the sequence of the groups in the rollup clause.

Cubes go even further by defining permutations for every combination of groups.

Window functions place individual records in the context of the dataset and enable the calculation of percentiles, rankings, and other measures.

Common t able e xpressions (CTE s) help us simplify complex queries by decomposing them into simple building blocks that act like local views. CTEs also enable recursive queries to handle hierarchical data structures, such as org charts or bills of materials.

Views and materialized views are created through DDL statements and become part of the database. The other constructs are created at query execution time and are ephemeral.

Figure 10.2 illustrates how all the components work together. The data in the normalized schema, logically replicated from the transactional systems, is transformed into a star schema that serves as the foundation for analytics queries.

Figure 10.2: Data transformation from the normalized model to the star schema

If the star schema is a finished house, the data vault is a set of LEGO blocks. Instead of forcing data into a rigid structure immediately, the data vault breaks information down into small, flexible, and reusable components. The data vault architecture was developed to simplify the integration of data from heterogeneous source systems (e.g., order management, e-commerce, and customer loyalty) and to provide a better way to handle the evolution of source schemas.

Data vaults use their own internal surrogate keys (Chapter 5, Transactions, ACID Compliance, and Data Normalization) to integrate business keys from different source systems. They use slowly changing dimensions of type 2 to track data changes over time, such as a product price change.

Hubs, links, and satellites are the core building blocks of the data vault.

  • Hubs (the ” w ho” and ” w **hat”)****:**Hubs represent core business concepts or entities. They contain only the unique list of business keys.
    • Examples: Customer, product, sales transaction.
      • Content: The stable business identifier (e.g., customer_id, product_sku) and metadata (load date, record source).
  • **Links (the relationships)****:**Links represent the associations or transactions between Hubs. They allow you to model relationships without forcing a specific reporting grain upfront.
    • Examples**:** A customer places an order; an order contains a product.
      • Content**:** The keys of the hubs that are being linked.
  • **Satellites (the context and history)****:**Satellites store all descriptive attributes and their historical records. This is where the actual context lives.
    • Examples: Product price, product bill of materials (BOM), customer contact information, sales order status.
      • Content: Attributes, validity dates, and metadata.

This separation into keys (hubs), relationships (links), and context (satellites) makes it easier to integrate data from different data models and to handle schema evolution in the source systems.

Figure 10.3 shows a sample data vault model for our application domain. It illustrates how data from multiple systems (e.g., the loyalty system) can be integrated by creating a customer loyalty satellite associated with the customer hub.

Figure 10.3: A sample data vault

Data vaults also make it easier to handle access control, as we can limit access to certain satellites to specific user groups. For example, only a controlled set of individuals has access to customer contact information.

Data vaults can be queried directly, or they can be used as the central backbone for data warehouses, from which we generate specific star schemas.

Relational online analytics processing (ROLAP)

Section titled “Relational online analytics processing (ROLAP)”

Star schemas and data vaults are sometimes referred to as multi-dimensional online analytical processing (MOLAP) to distinguish the process of creating an analytics-optimized data model first, before using cubes, groups, rollups, aggregates, and so on, from an approach in which analytics queries are run directly on the normalized data model. That latter approach is often called relational online analytics processing (ROLAP). While the ROLAP approach avoids data copying, it tends to perform more slowly because it does not leverage an analytics-optimized data model, and the database parameters (work_mem, jit, max_connections) cannot be optimized for analytics. The ROLAP approach, which avoids creating a star schema first, is sometimes chosen for its technical simplicity, since developers historically had to use third-party tools to build analytics-focused schemas. As we will see, today, PostgreSQL logical replication makes it very easy to develop an analytics-optimized data model that remains synchronized with the transactional model.

The ROLAP approach, which executes analytics queries on a transaction-optimized data model, should be used only for small datasets.

Comparing ROLAP, star schemas, and data vaults

Section titled “Comparing ROLAP, star schemas, and data vaults”

Table 10.1 compares the different data modeling approaches for analytics use cases.

ROLAPStar schemaData v ault
Data m odelNormalizedDenormalizedDenormalized or normalized
Query performanceLowHighMedium (if queried directly)
Complexity of implementationLowMediumHigh
Complexity of queryingHigh (many complex joins)Low (few joins)Medium (requires more joins)
Multi-system data aggregationNoLimitedHigh
Support for source-system schema evolutionYes (it works directly on the source system or a copy thereof)LimitedYes
Delayed dataNoDepends on implementationDepends on implementation
Best forOperational systemsSmall data warehouses, data marts, and BI reportsEnterprise data warehouses

Table 10.1: Comparing ROLAP to MOLAP

Star schemas are easy to implement and often the solution of choice, but they are limited in their ability to integrate data from multiple source systems. In complex enterprise environments, we recommend using a data vault approach to build data warehouses that aggregate data from heterogeneous source systems and then generate use-case-specific star schemas.

In the remainder of this book, we will focus on the creation and use of star schemas.

In this chapter, we reviewed three approaches to modeling data for analytics: the star schema, the data vault, and ROLAP, and discussed their strengths, weaknesses, and ideal use cases.

Data vaults are well-suited to integrating data from multiple systems and handling source-system schema evolution, but they are pretty complex. The ROLAP approach is very simplistic but suitable only for small, ad hoc reporting use cases. The star schema, often built on data vaults, is the most popular analytics model for relational databases. The star schema provides a solid foundation for PostgreSQL’s analytics capabilities: views, materialized views, groups, grouping sets, rollups, cubes, window functions, and common table expressions.

In the following chapters, we will look at how data can be moved from transactional systems to analytics systems using an extract-and-load process, and how normalized data from the transactional system can be transformed into a denormalized, analytics-optimized star schema.