пятница, 19 сентября 2014 г.

Handling Dimension Changes


Dimensional data changes constantly. Customers move, new products are introduced, employees get a salary raise, warehouses get new managers, and so on. One of the main challenges when building a data warehouse is how to adapt to these changes in such a way that all relevant history is captured and all transactions are linked to the correct historical dimension records. Some of these changes occur frequently, others only occasionally. Some changes affect a single record, and some involve complete tables, such as introducing a new customer classification. And some changes are relevant to store in a historically correct way for the organization, while others can simply replace old data. For all of these situations, a different strategy can be applied, and together they form the different ways of handling slowly changing dimensions (SCDs). In his first edition of The Data Warehouse Toolkit, Ralph Kimball introduced three different SCD strategies: overwrite, stack, and add. These strategies are now respectively called SCD type 1, 2, and 3 and will be described shortly. Over the years, many other people from the database modeling community added new types and variations to the original SCD types; the current approach covers the handling of all possible changes that can be applied to source data and how to handle these changes most effectively in a data warehouse.
The term slowly changing dimensions is slightly misleading in the sense that you might get the impression that these types should be applied to the complete dimension table. This is an incorrect assumption which we’d like to address before we go on. Each column in a dimension table should be treated individually. So it is possible that for some columns a type 1 is used, while for others the type 2 approach will be more appropriate. Other strategies or combinations can also be used, but identifying which strategy should be applied to each column is an important part of the design process. 
The story doesn’t begin with type 1, however. There is also a type 0, meaning either ‘‘do nothing’’ or ‘‘replace completely.’’ In both cases, this is not an advisable strategy, unless it concerns static dimension tables. The most prominent example of these are the Date and Time dimensions. It’s highly unlikely that the Year value of the date Jan. 20, 2008 will ever change. What can change, however, is a Fiscal Year classification but in that case values usually get overwritten (type 1) or stored in an additional column (type 3).

Not all dimension attributes will be used for analytical purposes and thus not all are of interest for historical correctness. Which attributes are analytical and which are details differs per industry and organization. In some cases, a phone number is just a customer dimension detail that can be overwritten when a new value is extracted from the source system. In other cases, the phone number is being used for analytical purposes and changes need to be tracked. When we analyze sales, it’s usually sufficient to group by city, not necessarily by street or address. In that case, the column city is an analytical attribute and the column address is a plain detail. 


SCD Type 1: Overwrite
A type 1 slowly changing dimension is the most basic one and doesn’t require any special modeling or additional fields. SCD type 1 columns just get overwritten with new values when they come into the data warehouse. Picture shows what a dimension record looks like before and after applying a type 1 dimension change. In this case, the customer moved to a new address on a certain date. 


Without additional knowledge, you have no way of identifying when this change happened, and even if you insert an extra column with a last modified timestamp you only know that something changed inside the record, not in which column this change took place. A type 1 overwrite approach is used for columns that are of interest for our users (otherwise the columns wouldn’t have been there in the first place), but only the current status of the data is relevant, even when looking at older transactions. Remember that when you overwrite a column like this and run a query, all results will show the content of the column as it is now, not the earlier value. 


SCD Type 2: Add Row
Type 2 is not ‘‘the next step’’ in terms of functionality or complexity but is actually a category of its own. All ETL vendors went out of their way to support type 2 SCDs with wizards, macros, and other add-ins over the last couple of years so nowadays you’ll be hard-pressed to find a tool without this support. Of course, Kettle/PDI also has this functionality in the Dimension Lookup/Update step. But what exactly does it do? SCD type 2 is about history preservation and enables an organization to capture changes to a dimension table to retrieve historical correct data when querying the data warehouse.
 Table 1 shows the same example as in the previous paragraph, but now you can track changes through time by adding a few extra fields. There are multiple ways of modeling this or storing multiple versions; the most basic one is to add only a valid_from timestamp to the dimension record. Omitting the corresponding valid_to timestamp adds extra complexity when trying to retrieve the correct version of the dimension entry, so mark this as a mandatory field for this type of change as well. Two other extra columns can often be found in type 2 supporting tables: a current_record column indicating the current version of the dimension record, and a sequence or version number that is incremented each time a new version of the record is added.


Now you can do lots of interesting things with this data. Suppose Mr. or Mrs. Humphries is a regular customer and orders something every month. What happens in your fact table when these transactions are loaded is that the ETL process looks at the valid customer record for each particular customer at the time of loading. This means that all order fact rows for the customer with ID 22321 (the source system customer number) will store customer_key 1 until May 1, 2008, and use customer_key 2 from that day on until the next change for this customer is applied. The example fact table is displayed in Table2. 

Now when you want to know how much revenue was generated in Toronto in 2008, and you run this query in September, the condition is where customer_city = 'Toronto’. The dimension record with the value 1 for customer_key is the only record satisfying this condition. And because the join is on customer_key, only the first four rows of the fact table are retrieved for this customer. When the condition is where customer_name = 'Humphries’, both customer_id 1 and 2 satisfy the condition and all the fact rows will be returned.


PROCESSING TYPE 2 SCD DATA
An ETL process, whether hand coded or coded with a tool, needs to have several capabilities for handling type 2 dimension changes. First of all, the incoming data must be compared to the data that already exists in the dimension table. The output of this process is the incoming data set with flags added for new rows (I for Insert) to be inserted, existing rows that need to be updated (U for Update), and possibly even deleted rows that don’t exist anymore in the source system (D for Delete). Based on the I, U, or D flags, the process then needs to assign new surrogate keys in case of inserts or updates. Inserts are easy: the new row can be added with the default settings for valid_to and current_record. For an update, additional processing is required: the existing row needs to be detected (that’s why the current_record indicator is so useful), the valid_to timestamps need
to be set to the correct value, and the current_record flag has to be set
to a value of 0, N, or whatever logic you have designed for it. Then a new record with the updated data has to be created, a surrogate key generated, and the appropriate timestamps and current_record flag need to be set. Because deleting dimensional data is out of the question (it probably still is referenced by existing facts) the records with a delete flag get their valid_to timestamp set. In addition, another indicator can be used to mark the record as deleted. A possible solution is to use a value other than 0 or 1 for the current_record flag. 


Of course there is more to capturing history in a data warehouse; this is just the plain version of historical correctness. For instance, think about the following issue: what point in time do we use for the valid_from and valid_to timestamps? Is it the time the change was entered in the source system? The time the data was loaded in the data warehouse? The actual time in the real world when the event took place? Or the time when we were notified of this event? The third option might seem the most appropriate version and the best representation of the actual event, but how do we track this? In some industries, such as the insurance business, all these timestamps need to be stored and the data warehouse should have a full account for the history of history, as it is called, as well.


SCD Type 3: Add Column
The type 3 strategy requires at least one extra column in the dimension table. When the data for a type 3 column changes, the existing value is copied to the extra _old column while the new value is placed in the regular column. Table shows an example of this. 


This might seem an odd way of keeping previous values at first, and in most cases it is. It’s only possible to handle one previous version. Storing additional changes requires an extra column for each version you want to keep. But imagine that your organization structure changes completely, or a completely new product group structure is introduced. In those cases, where all records change at the same time, it makes sense to use an extra column. Handling these massive changes with a type 2 scenario doubles the number of records in your dimension table and in most cases, only the new structure of the data is relevant. The old version is just kept for reference purposes or as a translation table.


SCD Type 4: Mini-Dimensions
Kimball’s dimensional modeling introduces the term mini-dimension. Some sources claim this to be a type 4 scenario; others use the term ‘‘type 4’’ for other purposes. The notions of type 4 and 5 SCDs were introduced in 1998 by Michael Schmitz, a renowned expert in data warehousing and dimensional modeling. We conform to this classification here, in contrast to other sources such as Wikipedia, which uses a different categorization.
Mini-dimensions solve two particular problems with changing dimension tables. One problem occurs when dimension tables get really big, say a customer dimension with 150 million rows (they exist!). The second problem occurs when changes happen very frequently, causing the dimension table to double or triple in size each year. The trick here is to first identify which analytical attributes change very frequently and put these as a group in one or more separate dimension tables. The result of this is one or more extra dimension keys in the fact table. 

Here’s an example. Suppose you have a large customer dimension table with the attributes city, region, country, gender, birth_date, and income. The first three fields can be categorized as geographic data; the latter three have a more demographic nature. Of course, the gender description doesn’t change very often but is probably one of the key attributes for analytical purposes. These six fields can therefore be put in two different mini dimensions, a dim_geography and a dim_demography.
Mini-dimensions do honor to their name: They usually are very small, not only in number of records but also in number of attributes, as in this example. There is, however, a tradeoff involved in order to keep this number of records as small as possible. When an attribute such as income is used in a mini-dimension, it’s impossible to store all possible different values so you need to work with banded values or ranges. Remember that when using fields A, B, and C for a mini-dimension, the number of records is determined by multiplying the number of possible values of A, B, and C. So if each age from 0 to 100 is used, the multiplier is already 101. It makes more sense to define age and income ranges, maybe 10 of each, resulting in 100 records. Multiplied by the three possible values for gender (male, female, and unknown) the number of rows in the mini-dimension will be 300, which is really small by any standard. Mini-dimensions with 100,000 rows are not uncommon and with the current state of technology also not a problem. If the mini-dimensions get any larger than that, it’s advisable to redesign the dimension table and maybe split it up again into smaller dimensions.
Table shows an example data model with a fact table and three dimension tables of which two are mini-dimensions.
In order to make this work you need to identify the correct mini-dimension key when loading the facts, which requires extra overhead. For instance, to determine the age group a customer belongs to, you need to calculate the age based on the load date and the customer’s birth date. The same goes for income band and all other attributes needed to determine the correct mini-dimension key. The payoff, however, is huge. Suddenly, many fewer changes can occur to your ‘‘main’’ dimension table. History is perfectly covered in the fact tables using the mini-dimension foreign keys, and to top it off, you also added the current mini-dimension key to the main dimension table. This last addition enables the user to use the mini-dimensions in conjunction with the main dimension without the need to query the fact table. In fact, this model serves two purposes: It gives the current dimension record value, which is very useful for selecting target groups—for example, for direct marketing campaigns—while retaining the full history of the analytical attributes in the fact table. 


SCD Type 5: Separate History Table
So far, the dimension changes have affected the way you look at your query results with respect to the corresponding fact rows. The different strategies enable you to identify which version of a dimension record was valid at the time of a transaction, be it a sale, an inventory movement, or some other business event. Type 5 is a little bit different because it cannot be used to run analytical queries that use the fact table as well. With type 5, a separate history table is created for a dimension table with the sole purpose of correctly capturing all changes to all attributes in the dimension table. A type 5 strategy is therefore an addition to the existing SCD types and should be used in conjunction with one or a combination of the other strategies. Type 5 history tables should therefore not be used for analytical queries involving fact tables. Table shows an example of this type of table together with the parent dimension table. 


This almost looks like a fact table, and indeed it has some of the same characteristics as a fact table. However, there are no real facts: There’s nothing to summarize because there are no measurable items. The only available option is to count the number of customers or changes, but that could be an interesting enough activity: How many times do customers get a new e-mail address? What’s the average moving rate?
Also note that the diagram in Figure 7-10 contains a change type table that serves as a lookup table that indicates exactly what values have changed. Next table shows the first few rows of this table so that you can get a feeling of what this data is all about.
Change types are also a perfect indicator for data quality issues. Look, for instance, at type number 4 where only the city name is changed. It’s highly unlikely that this happens without the change of address, postal code, and possibly telephone number as well. Regardless of whether you overwrite existing values in your customer dimension, changes should be tracked in the history table. The end effect is a full audit trail of changes to dimension data. Remember, however, that this serves a different purpose than the regular dimension and fact tables used for reporting and analysis.
The example described previously is only one of the many possible solutions for modeling a full data audit trail. Another common approach is to mimic the change or log tables used by many database management systems for replicating and synchronizing data between two or more databases. Besides the changed data, these change tables contain the record key, change timestamp, and the change type indicator I, U, or D for Insert, Update, and Delete. Sometimes before and after images are both present in these tables, comparable to a type 3 SCD scenario. 

SCD Type 6: Hybrid Strategies 

Type 6 doesn’t really exist but is sometimes described as 1+2+3=6, indicating that it is a mix of different strategies applied to a single dimension table. Kimball gives an example of this in The Data Warehouse Lifecycle Toolkit. A common business request is ‘‘I want to see all product revenue according to the current version of the product group.’’ This query cannot be answered if a product group is handled as a type 2 attribute, which is usually the case. One way to solve this is to add an extra product attribute to the dimension table where the current version of the product group is stored for all versions of the product. Table above illustrates this feature.  By using this modeling technique, you can still store the correct version of the product in your fact table for historical correctness, but this technique also enables a user to look at this information as if all history were based on the current product group classification. This is, however, not a very flexible solution and works only for one or a few attributes. Another way of solving this problem is joining the same dimension table on the source ID, and restricting the extra joined table on the current record. By doing this, all attributes can be used ‘‘as is’’ while at the same time retrieving the full history from the fact table based on the SCD keys. The last option is to add an additional dimension table with only the current values in it. This current dimension table will then get its own key in the fact table. A drawback of this solution is that you need an extra key column in the fact table for each current dimension you add this way.



Unknown Dimension Keys

In addition to the already-mentioned advantages for using surrogate keys (and the upcoming explanation in this chapter of handling history in the data warehouse), there is another good reason to use surrogate keys. Sometimes data will be loaded in a fact table and no corresponding dimension key can be found based on the natural key and/or the validity of the dimension record. For those cases, you need a mechanism that stores the facts anyway to make sure that no data is omitted during processing. For this reason, we recommend having an unknown record in each dimension table. Key generation in a dimension usually starts at 1, so that leaves the number 0 as a perfect candidate for the unknown dimension record key. This record should have a value of ‘‘unknown’’ in all attribute fields. Picture below shows a partial example of the unknown record in a customer dimension table. 

Modeling Date and Time


Date and time seem trivial subjects at first, but when you think about it for a couple of seconds there’s a lot more to it. For instance, think about how you would account for different time zones your organization operates in. Or think about how to handle fiscal years that are out of sync with the regular calendar year. The week numbering in Europe is based on ISO 3306, whereas in the U.S. week numbering starts at 1 on January 1, causing possible differences in results when an EU subsidiary reports weekly results to a U.S.-based head office. ISO also has a different year calculation, which means that the ISO year for a date can differ from the calendar year of the same date. And how would you model date and time? What granularity do you want to use? We give you our thoughts on the subject here and a couple of hints and best practices to get you started, but ultimately the design decisions should be made by you based on the case at hand.

Time Dimension Granularity
Sometimes when people start with designing a dimensional model, they think that date and time should be stored in a single dimension table. This assumption is perhaps not entirely wrong, but usually not the best one to make. Suppose you want to be able to reference a date-time dimension by seconds. There are 24 × 60 × 60 seconds in each day. For a year consisting of 365 days, you would need 31,536,000 rows in the dimension table, and because you usually store 10 or more years, that adds up to over 315 million rows. Doesn’t look like a sensible approach. The most extreme alternative is to create a dimension table per date-time part. In that case, you’d have to create dimension tables for year, month, day, hour, minute, and second. These tables would all be very small but would require six foreign keys in the fact table. This is also not a very good approach. It’s best to stay somewhere in the middle between these two extremes by creating one date and one time dimension. Even in the case where you would need your transactions to reference a specific second, the dim_time table would only contain 86,400 rows. Our sample WCM data warehouse uses a time dimension by minute, which is only 1,440 rows.

Local Versus UTC Time
When dealing with time, you must also consider the challenges presented when your organization covers multiple time zones. In that case, it might be beneficial to add both local and UTC time to the time dimension table so any transaction can always be looked at from different perspectives.

UTC is an international standard time and time notation governed by the ISO 8601 standard. The acronym is a compromise between the French TUC (Temps Universel Coo ̈rdonne ́) and the English CUT (Coordinated Universal Time). Anyone familiar with military terminology might have heard of ‘‘Zulu time,’’ which is the same as UTC. International time zones are indicated as UTC plus or minus a number of hours. This offset can even vary over time when countries change the daylight savings start or end date, or when a government (for example, Venezuela) decides to deviate from international standards. The fixed offset in our time dimension table is therefore a simplification of the real world. 


Smart Date Keys
There is one exception to the use of meaningless surrogate keys—the key for the date dimension. We prefer to use an integer in the form YYYYMMDD for two reasons. First, this key can be easily generated from an incoming date and therefore saves a lookup operation on the date dimension table. Second and probably more important is the fact that this numbering scheme can be used to partition your fact tables. Table partitions can also get a name with a date number extension to easily identify, such as P_200808 for all the August 2008 transactions. Other than these two reasons, the use of a smart date key is prohibited and can under no circumstances be used directly in queries on the fact table without joining the corresponding date dimension table.

Handling Relative Time
In many cases, we are not interested in a specific time period such as a week or a month, but want to know what a specific time period looks like compared to another one. The question is how to set up the time dimension to handle relative time, such as last week, last month, or same month last year. Of course, you can write SQL to retrieve the corresponding rows from the database but then you either need to adjust the statement for each new period, or need to use functions and expressions to make a statement dynamic. The examples in the following query blocks show what we mean. The first query retrieves the result from the current and last month, but the statements are hard coded: 


SELECT d.year4, d.month_number, f.sum(revenue) AS revenue FROM fact_sales AS f
INNER JOIN dim_date d ON f.order_date_key = d.date_key
WHERE d.year4 = 2008 AND d.month_number BETWEEN 7 AND 8

A dynamic version might look something like this:

page214image3808








This will work fine, except when the current month is January. To avoid complex coding like this it’s better to add additional columns to the time dimension table that can be updated during the ETL process. As an example, we’ll use two columns: current_month and last_month. When applicable, they will contain the value 1, otherwise 0. The same technique can be applied to indicate year to date, month to date, and so on.
Another technique we’d like to mention is the use of offsets to be able to perform date arithmetic in a simple way. A good example of this is the use of Julian dates, which are consecutive integer values. This makes it very easy to filter on the last 30 days or 30 days prior to a chosen date. Again, you can expand this to weeks, months, and years as well. By setting the current week, month, or year to 0 and counting backwards, it’s possible to have both a current period indicator and a means of filtering on the last three months, last six quarters, etc.

Table below shows a partial collection of rows and columns from the time dimension to illustrate this technique. The current date in this example is July 1, 2009 with a week starting on Monday.
In this table, you can see three ways of handling relative time:
  • True/false indicators—The current and last week columns are updated each week. Retrieving the current week is a matter of adding current_week = 1 to a query.
  • Sequence number—The Julian date is an integer that allows for simple arithmetic, e.g., ‘‘last 30 days.’’ Any date can be used as the offset (starting point).
  • Sequence with offset 0—This combines the first two options in one column. Current week is always 0, last week –1, and so on.
The third option might appear to be the ideal solution to handle all relative time issues, but there’s a catch. The extra current and last week columns with just 1 and 0 enable you to do calculations as well. In many cases, you need
to see current and last week’s revenue side by side, and this can easily be accomplished by using a statement like the following:
 








Querying Star Schemas


First of all, if you want to really learn how work with SQL, you can learn it on sql-ex.ru for free.

So far, you’ve seen diagrams linking dimension and fact tables together, but in a database these are just tables. The relations in the diagrams are foreign key constraints, which means that it will not be possible to insert a product key into the orders fact table if this key does not exist in the dim_product dimension table. Getting data out of the database is another thing. For this, you need a query language called Structured Query Language, or SQL. If you’re not familiar with SQL, don’t worry—the SQL you need for retrieving information from a star schema is not very complicated. And although this book is not a SQL text, we cover enough of the basics here to enable you to start writing queries to retrieve data from dimensional data marts. All we need for this is the SELECT statement, a way of joining the different tables together, and an understanding of how to group the results from the query. For starters, have a look at the basic SQL building blocks for selecting data:

  • SELECT—A list of the columns, constants, and expressions you want to retrieve from the database.
  • FROM—The tables and views that contain the data you need, including the relationships between those tables and views.
  • WHERE—The restrictions you want to apply to the data in the selected tables, views, and expressions, excluding the aggregations.
  • GROUP BY—Specifies the summary level of the query. All non-aggregate columns and expressions in the SELECT list should be part of the GROUP BY statement.
  • HAVING—Contains conditions on summarized expressions, e.g., having sum (revenue) > 100,000.
  • ORDER BY—Denotes the order in which the results will be displayed.

If only the total revenue is needed from the fact table, there’s no need to use
JOINs or GROUP BY clauses, just the following: 

SELECT SUM(revenue)   FROM fct_orders

This little query doesn’t tell you very much, so you can add the date dimension to calculate the revenue by year:

SELECT date_year, SUM(revenue)
FROM fct_orders
JOIN dim_date
ON fct_orders.date_key = dim_date.date_key GROUP BY date_year


Now you have a simple query that is the basis for all other possible queries that can be executed against a dimensional data model. The first line with the SELECT clause tells the database what the result set will look like. Next, you need to tell where the data is retrieved from by using the FROM clause.
You also want to JOIN another table and you need to tell the database which columns the join will be based on—in this case, the date_key in the dimension and fact tables. Finally, the results are grouped by all elements of the SELECT statement that are not part of an aggregate function. For example, when the SELECT statement looks like this:

SELECT date_year, product_type, product_name, SUM(revenue), SUM(quantity)

the GROUP BY statement needs to be

GROUP BY date_year, product_type, product_name


To complete this query all you need to add are the FROM and JOIN parts:



The SQL examples used so far still lack the use of aliases. An alias is another name you can use to refer to a table, column, or expression. Although they are not always required, it’s good practice to always use them. Adding the alias total_revenue to the expression SUM(revenue) gives more meaning to the result column, and using aliases for table names enables a shorthand notation of the join conditions. Compare the following JOIN clauses to understand what we mean by that:

FROM fct_orders
JOIN dim_date ON fct_orders.date_key = dim_date.date_key


versus

FROM fct_orders AS f
JOIN dim_date AS d ON f.date_key = d.date_key


There are cases in which the use of aliases is not optional but required. The first practical case where aliases are at least very helpful is when the same column name appears in more than one table of the set used in the query. Suppose that in the previous example you wanted to include date_key in the result set. Because this column is part of both the fact and the dimension table, the SQL parser cannot determine which table to pick the column from, so you need to include the table reference in your SELECT statement—for example, SELECT dim_date.datekey. Now it’s immediately obvious that the use of a short alias such as d will save a lot of typing. The complete query statement, including the use of aliases, now looks as follows:



The second case where aliases are not only practical but required is when the same table is used in different roles. An example is a query that asks for all revenue by product type with an order date in 2007 and a ship date in 2008:
  


The WHERE part of this query is covered in more detail shortly. 

Fact Table Types


Fact tables are not always based on transactions alone. Transactional fact tables are the most commonly used type, but there are a couple of variations you need to be aware of. The first one is the accumulating periodic snapshot table. This sounds more complicated than it actually is; the only difference between a regular fact table and this one are the date fields tied to a specific process that need to be updated when new events occur. Take, for instance, World Class Movie’s rental process where DVDs are ordered on an order date, shipped on a ship date, and returned on a return date. Because we don’t want to wait until the process is completed to begin entering the data, we start by adding the fact row to the data warehouse when the order is placed and subsequently accumulate this row with the correct dates as they become known.

A rather different type of fact table is the periodic snapshot, which is like a picture taken every day, week or month. Periodic snapshots are used when you need to freeze data that are only indirectly linked to transactions. A good example in the WCM data warehouse is the DVD inventory. Inventory levels change constantly and there is no way to keep track of these over time by using a transactional fact table. The only option here is to periodically take a snapshot that enables you to report on inventory level increase or decrease over time.
Another way of looking at transaction and snapshot fact tables is by the types of measures that they contain. Measures in a regular transaction table, like sales revenue, can be summarized across all dimensions, including time. These are referred to as additive facts or measures. The measures in a periodic snapshot table cannot be easily summarized, at least not when multiple periods are involved. For example, summarizing the weekly SKU articles stock levels does not give you a total yearly stock! These measures are called semi-additive, meaning that you can add them together but need to include a time or period filter to slice the data.
The last type of measure is the non-additive fact. A good example of this is room temperature. It doesn’t make sense to summarize the temperature of different rooms or different periods, although you can always calculate averages. 

Dimension Tables and Fact Tables


The next question is, of course: What’s the difference between dimension and fact tables, and what makes something a fact table? As you will see later, the distinction is not always clear, and there are even occasions when a dimension table in one star schema can become a fact table in another star schema. A simple explanation is that dimension tables contain information about business entities (customers, products, stores) and fact tables about business events (sales, shipments, orders). The most notable difference is in the measureable columns such as revenue, cost, and items, which are part of the fact tables. Also, all of the different angles and attributes that are required to summarize these facts are stored in the dimension tables. It’s actually pretty simple if you translate a typical report request such as ‘‘Show me the total order value per month per product group’’ into a dimensional model.

 The calculated item of interest (sum of order value) is a fact, month is a ‘‘time’’ attribute belonging to the time dimension, and ‘‘product group’’ is a product attribute belonging to the product dimension. A fact table therefore contains only foreign keys pointing to the dimension tables and attributes that can be aggregated (quantitative elements). Dimension tables contain all attributes that describe a certain organization perspective (qualitative elements).
 

This data mart gives you very little information because it contains only a few measurements and two dimensions. Nevertheless, it’s a good starting point to illustrate how exactly a dimensional model works:

  • All fact rows are stored at the lowest possible granularity level. By granularity, we mean the grain of the data; a fact table at the date level has a lower granularity than a fact table at the month level.
  • The granularity of the fact table is determined by the combination of the granularity of the dimension tables. In the example, this means that for each combination of product and date there is a possible fact row. Not all combinations need to be present, of course!
  • All measures in the fact table can be rolled up or grouped by the elements of the dimension tables, so this little data mart can calculate revenue by year, month and product group, or by year and product type, or any other desired combination.

You could argue that an order is also a business entity and only the order lines with the individual transactions are facts. In a way, that assumption is correct. This is a case where special attention is needed in modeling the data marts. Later in this chapter we’ll explain what special attention is needed and describe other more advanced dimensional modeling topics. For now, it suffices to keep the simple definition in mind. 


What is Star Schema?


The first thing you might ask is: Why are these database models called ‘‘star schema’’? Probably because the entity-relationship diagram of this kind of schema resembles a star. The center of the star consists of a large fact table and the points of the star are the dimension tables. Most users first encounter a star schema in a sales data mart with customers, products, stores, promotions, and time.



It’s the modeling technique that counts, not the number of dimension tables used. One of the obvious benefits of using a schema like this is its simplicity and understandability for end users. Very often during the design phase of a data warehouse, star schemas are used to draw the initial translation of business questions into logical database diagrams.