QlikSense dimension historization

Publications

Qlik Sense Dimension Historization: Reconstruct the Past Without Falsifying It

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

In April you reassigned a salesperson's portfolio. In July you opened the commission dashboard and discovered something uncomfortable: January's sales appeared assigned to the new salesperson. Nobody touched an invoice. Nobody manipulated data. Simply put, your customer master file stores who handles the account today, and your model assumed that was also true yesterday. That is where the QlikSense dimension historization it stops being a technicality and becomes a money problem.

QlikSense dimension historization
Model with bridge table: the facts preserve the context in effect on each date.

I have seen this flaw in companies with mature ERPs, competent BI teams, and flawless dashboards. However, it is not a programming error. It is an error of assumption: believing that a dimension is a photograph, when in reality it is a movie. And while your fact table stores every transaction with its date, your dimension table stores only the last frame.

In this article I show you how to solve it with the script, not with front-end patches. You will see the complete pattern of QlikSense dimension historization using extended IntervalMatch, with quality controls included.

The real problem: your data master deletes the history

Think for a moment about everything that changes in the master data and alters the number: the assigned salesperson, the price list, the customer segment, the payment term, the plant that manufactures an SKU, an employee's cost center. Consequently, each of those fields silently rewrites your past when updated.

The consequences are not theoretical. First, commissions are paid to the wrong person. Second, profitability analysis by segment is distorted because customers who upgraded drag their history into the new group. Finally, evaluating a pricing campaign becomes impossible, because the list price you see today is not the one that applied back then.

In fact, Gartner puts the average cost of poor data quality in an organization at about $12.9 million annually. Furthermore, distrust in data for decision-making rose from 55 percent in 2023 to 67 percent in recent measurements. And there is a statistic that should concern any manager investing in artificial intelligence: Gartner projects that organizations will abandon nearly 60 percent of their AI projects due to insufficient data quality.

💡 Key point: A fact table without historized dimensions does not store the past. It stores the present projected backward, which is a very different thing.

What is a slowly changing dimension

The discipline of data warehousing has had a name for this for decades: slowly changing dimensions, or SCD for short. Now, type two is the one we are interested in here. Instead of overwriting the record when an attribute changes, it preserves the old record and inserts a new one. Thus is born the QlikSense dimension historization What are we going to build?.

That schema needs three control columns. First, an effective start date. Second, an expiration date. Third, an active record flag. With that, each row becomes a permanent snapshot of a time span, and the report can answer «what it was like» instead of just «what it is like».

Now, type two comes with a cost: the table grows with every change. In large and volatile dimensions, that growth degrades scan performance. That is why the decision of what to track historically is just as important as knowing how to do it, and I will return to that point in the best practices.

How QlikSense dimension historization works with IntervalMatch

Qlik Sense solves the problem with a script prefix called IntervalMatch. Its extended version links discrete values, such as the date of a sale, with numerical intervals, such as validity ranges, and also respects one or more grouping keys.

Now, before the code, it is worth reviewing three rules that the official documentation makes explicit and that almost everyone discovers late. First: the discrete field must already be loaded in memory before the IntervalMatch; the prefix is not read from the database. Second: the table of IntervalMatch it must contain exactly the two interval fields, plus the grouping keys. Third, and the most dangerous: the intervals are closed, meaning both ends are included.

That third rule explains a classic duplication. If leg A ends on April 30 and leg B starts on April 30, any sale on that day falls into both legs and is counted twice.

The QlikSense dimension history script, commented

Let's go to the full pattern of QlikSense dimension historization. In fact, I've used it as is in production to track the history of salesperson portfolios and customer segments.

// =========================================================
// 1) FACTS — comes first: IntervalMatch requires the
//    discrete date to already be loaded into memory
// =========================================================
Sales:
LOAD
    InvoiceNo,
    CustomerID,
    Date(SalesDate)                                   as SalesDate,
    AutoNumber(CustomerID & '|' & Num(SalesDate),
               'CustomerContext')                           as %CustomerContext,
    Sales,
    Margin
FROM [lib://QVD/fact_sales.qvd] (qvd);

The key %CtxClient is the heart of the design. It combines client and date into a single field and then compresses it with AutoNumber(). This avoids a surrogate key between the fact table and the bridge, and also significantly reduces memory consumption.

// =========================================================
// 2) VALIDITY PERIODS — the master record's change log
// =========================================================
Valid Periods:
LOAD
    CustomerID,
    SalespersonID,
    CustomerSegment,
    Date(StartDate)                                   as StartDate,
    // An open interval closes in the future; it is NEVER NULL
    If(Len(Trim(EndDate)) = 0,
       Date(MakeDate(2099,12,31)),
       Date(EndDate))                               as EndDate
FROM [lib://QVD/dim_cartera_vigencias.qvd] (qvd);

that If() about End date It seems cosmetic; however, it is critical. The current section usually comes with a null expiration date, and that is why IntervalMatch Discard those intervals with undefined limits. Consequently, without that replacement you precisely lose the current segments, which are the ones the business consults the most.

// =========================================================
// 3) QUALITY CONTROL — overlaps and gaps, before crossing
// =========================================================
ValidityCheck:
LOAD
    CustomerID,
    If(CustomerID = Previous(CustomerID)
       and StartDate <= Previous(EndDate), 1, 0)   as OverlapFlag,
    If(ClientID = Previous(ClientID)
       and StartDate > Previous(EndDate) + 1, 1, 0) as GapFlag
RESIDENT Validity
ORDER BY CustomerID, StartDate;
Summary:
LOAD Sum(OverlapFlag) as Overlaps, Sum(GapFlag) as Gaps
RESIDENT ValidityCheck;
LET vOverlaps = Peek('Overlaps', 0, 'Summary');
LET vGaps  = Peek('Gaps',  0, 'Summary');
TRACE >>> Validity periods with overlap: $(vSolapes) | with gaps: $(vHuecos);
DROP TABLES Summary, ValidityControl;

This block does not transform anything: it audits. Previous() compare each row with the previous one according to the loading order, that is why ORDER BY It is mandatory. If the trace reports overlaps, you are guaranteed to have duplication. If it reports gaps, you will have sales without an assigned salesperson.

// =========================================================
// 4) BRIDGE — Extended IntervalMatch, grouped by CustomerID
// =========================================================
TempBridge:
IntervalMatch (SalesDate, CustomerID)
LOAD StartDate, EndDate, CustomerID
RESIDENT Validity;
// Bring historical attributes into the bridge
LEFT JOIN (BridgeTmp)
LOAD CustomerID, StartDate, EndDate, SalespersonID, CustomerSegment
RESIDENT ValidityPeriods;
// =========================================================
// 5) HISTORICAL CONTEXT — same key as the transactions
// =========================================================
CustomerContext:
LOAD DISTINCT
    AutoNumber(CustomerID & '|' & Num(SaleDate),
               'CustomerContext')                           as %CtxCliente,
    SalespersonID                                         as HistoricalSalesperson,
    CustomerSegment                                    as HistoricalSegment
RESIDENT PuenteTmp;
DROP TABLES PuenteTmp, Vigencias;

The aggregator CustomerID inside of IntervalMatch prevent a customer's dates from overlapping with another's intervals. In fact, without that key, the junction table explodes: the documentation warns that overlapping intervals without grouping can generate millions of records.

// =========================================================
// 6) CURRENT TEACHER — today's photo, deliberately set aside
// =========================================================
Customers:
LOAD
    CustomerID,
    CustomerName,
    SalespersonID    as CurrentSalesperson,
    Segment      as CurrentSegment
FROM [lib://QVD/dim_clientes.qvd] (qvd);

This final step turns a technical exercise into a management tool. Thus, the QlikSense dimension historization it offers you two simultaneous lenses with unambiguous names.

// "As it was": commission for the salesperson who actually handled the sale
// Dimension: HistoricalSalesperson
Sum({} Sale * CommissionRate)
// "Current situation": measures the current portfolio against the historical data
// Dimension: CurrentSalesperson
Sum({} Sales)

Business impact: two questions you couldn't separate before

The first question is one of justice and compliance: whose responsibility is this commission? Therefore, the correct answer uses Historical Seller. Without historization, that settlement is incorrect, and furthermore, the claim still arrives even if no one detects it in the system.

The second question is about management: how is the portfolio I gave to this salesperson performing today? Instead, that response uses CurrentSeller and compare apples to apples when evaluating a reassignment. Both questions are legitimate. That is to say, the classic mistake is not choosing poorly, but rather being unable to choose.

There is a third effect, less obvious and more valuable. When the list price is historicized, you can finally measure the real effect of a commercial policy. This way you know what price applied on each date, how much discount was granted on it, and how volume responded. Ultimately, without that context, any elasticity analysis is just a well-presented guess.

Common errors in Qlik Sense dimension historicalization

These are the four mistakes I've had to correct the most in projects of QlikSense dimension historization.

⚠️ Common error: leave the end date as NULL for the current segment. IntervalMatch Ignore the intervals with undefined limits, so you lose exactly the current records. Close them with a distant date or use NullAsValue.

Error two: omit the grouping key. A IntervalMatch without CustomerID cross every date with every segment of every customer. Therefore, the model blows up, the reload takes forever, and the numbers end up multiplied.

Error three: replace the current master with the historical one. Some systems record history and then delete the current dimension. As a result, the sales manager loses their view of the current portfolio and ends up exporting to Excel, which is the most elegant way to ruin the project.

Error four: trusting origin dates without validating them. Historization only works if timestamps are consistent. That is why the overlap and gap control block is not optional: it is the difference between a reliable historical record and a purely decorative one.

Best practices from real-world implementation

These four rules summarize what was learned by taking the QlikSense dimension historization To production.

First, record historically only what changes the number. Vendor, price list, segment, plant, and cost center are usually enough. The customer's trade name or phone number do not deserve an additional row for every change.

Second, name the fields unambiguously. Thus, Historical Seller and CurrentSeller explain themselves in a meeting. Instead, a field called Seller just that guarantees a twenty-minute discussion every quarter.

Third, persist the validity table as an auditable QVD. That file is your evidence in the event of a commission review or internal audit. Furthermore, it allows you to rebuild the model even if the source has already overwritten the master.

Fourth, publish the quality control result on the dashboard itself. In fact, a traffic light system showing overlaps and gaps detected in the last reload is worth more than a hundred lines of log that no one reads.

Conclusion: the past is also data that is managed

In fact, most BI projects invest all their effort into the fact table and treat dimensions as a static catalog. However, the catalog also has history, and that history decides whether your numbers are defensible or merely plausible.

The QlikSense dimension historization It does not require new licenses or a complete redesign. It requires a validity table, a IntervalMatch well grouped, a composite key, and discipline to validate the ranges with each reload. It's an afternoon of work that prevents years of arguments.

I am leaving you a concrete test to validate your QlikSense dimension historization this week. Take a sale from a year ago and ask your application who handled it. Then contrast that answer with the actual record from that time. If they don't match, your dashboard isn't describing the past: it's rewriting it.

You can find more practical content on modeling, data governance, and technology leadership at hectorpincheira.com, where I publish Strategic Circle material every week.

Sources consulted: Qlik Help — Matching intervals to discrete data, Actian — The costly consequences of poor data quality and DEVOPSdigest — The data quality crisis undermining enterprise analytics.

Most Read

QlikSense Hierarchy: parent-child chart of accounts expanded by levels
QlikSense Hierarchy: the Chart of Accounts That Doesn't Add Up
QlikSense Sum TOTAL: share of each family over the total
QlikSense Sum TOTAL: the Percentage That Changes When You Filter
SAP Business One Inventory Revaluation - featured image of the tutorial
SAP Business One Inventory Revaluation: Fix Wrongly Loaded Costs
Empty chamber with wooden benches: the counterweight that required being present to be used
The Veto You Had to Say in Person: Your Decisions With No Counterweight
SAP Business One customizations - featured image of the pre-upgrade audit tutorial
SAP Business One Customizations: Pre-Upgrade Audit
SAP Business One Customer Concentration - featured image of the tutorial
SAP Business One Customer Concentration: Measure Your Risk with SQL

RELATED ARTICLES