Sub topic 12
Turning a flat table into facts and dimensions in Power Query
This chapter assumes you can open Power Query Editor, read basic M syntax, and recognize primary and foreign keys. You should also know the star schema ideas from earlier chapters: grain, fact tables, dimension tables, and one-to-many relationships. Here you split one wide import into a fact table and dimension tables, and you check that the split lost no information.
The starting point: one flat table
Many sources arrive as a single wide table. Each row is one order line, and it repeats the product and customer descriptions on every row. Here is a small flat query, SalesFlat, with inline data so you can paste it into a blank query and run it.
let
Source = #table(
type table [
OrderNumber = text, OrderLineNumber = Int64.Type,
OrderDate = date, ShipDate = nullable date,
ProductID = Int64.Type, ProductName = text,
Subcategory = text, Category = text,
CustomerID = Int64.Type, CustomerName = text, City = text,
Quantity = Int64.Type, SalesAmount = number
],
{
{"SO1001", 1, #date(2025, 1, 5), #date(2025, 1, 8), 101, "Road Bike", "Bikes", "Vehicles", 1, "Ana", "Lyon", 1, 1200},
{"SO1001", 2, #date(2025, 1, 5), #date(2025, 1, 8), 205, "Helmet", "Accessories", "Gear", 1, "Ana", "Lyon", 2, 80},
{"SO1002", 1, #date(2025, 1, 9), null, 101, "Road Bike", "Bikes", "Vehicles", 2, "Ben", "Turin", 1, 1200}
}
)
in
SourceThe grain is one row per order line, identified by OrderNumber plus OrderLineNumber. Every column falls into one of three groups:
- Keys and numeric measurements stay in the fact table:
Quantity,SalesAmount, and the key columns. - Descriptive columns that depend on a product or customer move to dimensions.
- Dates become keys that point to a date dimension.
The plan: one staging query, several outputs
Do not import the flat table once per output. Keep SalesFlat as a staging query and build each output from a reference to it. In Power Query Editor, right-click SalesFlat and choose Reference. Using Duplicate copies the whole source step, so the source is read again for every output. A reference starts from the staging query's result.
After creating the outputs, right-click SalesFlat and clear Enable load. The wide table then stays out of the model, where it would only add size and invite wrong relationships.
Building a dimension
A dimension has one row per member. For products, select the product columns and remove duplicate keys. This is the pattern from the topic plan:
let
Source = SalesFlat,
ProductColumns = Table.SelectColumns(Source, {"ProductID", "ProductName", "Subcategory", "Category"}),
DimProduct = Table.Distinct(ProductColumns, {"ProductID"})
in
DimProductTable.Distinct with a column list keeps the first row for each ProductID and silently drops later rows. That is a problem if the source disagrees with itself. Suppose product 101 appears once as "Road Bike" and once as "Road Bike 2024". Your dimension would show whichever row came first, and nothing would warn you.
Check for conflicting descriptions
Before trusting the dedupe, run a check query. It removes duplicates across all the product columns, then counts how many versions each key has.
let
Source = SalesFlat,
ProductColumns = Table.SelectColumns(Source, {"ProductID", "ProductName", "Subcategory", "Category"}),
FullyDistinct = Table.Distinct(ProductColumns),
Versions = Table.Group(FullyDistinct, {"ProductID"}, {{"Versions", each Table.RowCount(_), Int64.Type}}),
Conflicts = Table.SelectRows(Versions, each [Versions] > 1)
in
ConflictsAn empty result means each ProductID has exactly one description, so it is safe to use as a dimension key. If rows come back, fix the problem upstream or decide which version wins, for example by sorting and buffering before the dedupe. Do not leave the choice to row order.
The customer dimension follows the same steps. Keeping the key and the descriptive columns is enough:
let
Source = SalesFlat,
CustomerColumns = Table.SelectColumns(Source, {"CustomerID", "CustomerName", "City"}),
DimCustomer = Table.Distinct(CustomerColumns, {"CustomerID"})
in
DimCustomerBlank keys and missing members
Two problems come up often with real data:
- A null or empty key in the flat table produces a dimension row with a blank key. Filter it out of the dimension, and decide what the fact table should do with those rows. A common choice is an "Unknown" member with its own key, such as
-1, so that the facts still match a dimension row. - A key that appears in the fact table but not in the dimension shows up in visuals as a blank category. After you load the model, check for these orphaned keys.
Building the fact table
The fact query keeps the grain columns, the keys, and the numeric columns. It drops everything descriptive. It also turns each date into an integer key that matches the DateKey column of your date dimension.
let
Source = SalesFlat,
Kept = Table.SelectColumns(Source, {
"OrderNumber", "OrderLineNumber", "OrderDate", "ShipDate",
"ProductID", "CustomerID", "Quantity", "SalesAmount"
}),
WithDateKey = Table.AddColumn(
Kept, "DateKey",
each Int64.From(Date.ToText([OrderDate], "yyyyMMdd")), Int64.Type
),
WithShipDateKey = Table.AddColumn(
WithDateKey, "ShipDateKey",
each Int64.From(Date.ToText([ShipDate], "yyyyMMdd")), Int64.Type
),
Sales = Table.RemoveColumns(WithShipDateKey, {"OrderDate", "ShipDate"})
in
SalesThe yyyyMMdd text format gives the same number as the DAX formula YEAR * 10000 + MONTH * 100 + DAY used for the Date table. The two must agree exactly, or the relationship will not match any rows. Date.ToText and Int64.From both return null for a null input, so an order with no ship date yields a null ShipDateKey and no error. That row simply does not match any date through the ship-date relationship.
After shaping the fact table, check three things:
- Row count. It must equal the row count of
SalesFlat. Splitting columns must never add or remove rows. - Grain.
OrderNumberandOrderLineNumbertogether must be unique. Use Column profile or a grouped count to confirm. - Data types. Keys are whole numbers, and
SalesAmountis a decimal or fixed decimal number. Text-typed keys work but compress worse and join more slowly.
Natural keys or surrogate keys
The examples above reuse the source's ProductID as the dimension key. This is a natural key. It is simple and often enough. A surrogate key is a new integer generated by the model, and you need one when the source keys are unreliable. Typical cases are keys that are text with mixed formats, keys that get reused over time, or the same key coming from two systems.
To add one, create the index in the dimension, then merge it into the fact table:
let
Source = SalesFlat,
ProductColumns = Table.SelectColumns(Source, {"ProductID", "ProductName", "Subcategory", "Category"}),
Distinct = Table.Distinct(ProductColumns, {"ProductID"}),
DimProduct = Table.AddIndexColumn(Distinct, "ProductKey", 1, 1, Int64.Type)
in
DimProductThe fact query then uses Merge Queries on ProductID with DimProduct, expands ProductKey, and removes ProductID. Each merge adds work at refresh time, so use surrogate keys only when you have a reason.
Reference tables and model performance
The way you build these queries affects refresh time and model size:
- Disable load on
SalesFlat, as shown above. - Remove columns early. Each output should select only the columns it needs.
- Prefer steps that Power Query can send back to the source as one query (query folding). Selecting columns, filtering rows, and removing duplicates usually fold against a relational source. Adding index columns and some merges may not.
- If the flat table comes from a database, consider building the dimensions in the database as views. Shaping there is usually faster than shaping in Power Query.
After shaping: relationships
When you close and apply the queries, go to Model view and check the relationships. Power BI may detect some automatically, so verify each one:
| Relationship | One side | Many side | Direction |
|---|---|---|---|
| DimProduct to Sales | `ProductID` | `ProductID` | Single |
| DimCustomer to Sales | `CustomerID` | `CustomerID` | Single |
| Date to Sales (active) | `DateKey` | `DateKey` | Single |
| Date to Sales (inactive) | `DateKey` | `ShipDateKey` | Single |
The last row is the role-playing case. The fact table has two date keys and the model has one date dimension, so only one of the two relationships can be active at a time. A later chapter covers USERELATIONSHIP for that.
Common mistakes in this step
- Forgetting to disable load on the staging query. The flat table stays in the model, and users can build visuals from it that bypass the dimensions.
- Deduplicating on the wrong columns. If you pass the whole column list to
Table.Distinct, a key with two spellings creates two rows. The relationship then fails because the "one" side is not unique. - Leaving descriptive columns in the fact table. The model then stores the text on every fact row, and the same attribute exists in two places.
- Changing the grain by accident. A merge that matches more than one row multiplies fact rows. Compare row counts before and after.
Exercise
You build DimProduct with Table.Distinct(ProductColumns, {"ProductID"}). Power BI refuses to create a one-to-many relationship from DimProduct[ProductID] to Sales[ProductID] and reports that the column is not unique. A check shows that SalesFlat contains no duplicate dimension keys after the dedupe. What other cause should you check, and how?
Show answer
Check for blank (null or empty) ProductID values and for keys that differ only in case or trailing spaces. Power Query treats "A1" and "a1 " as different values, but the model's key comparison can treat them as the same, so two dimension rows collide. Fix it by trimming and standardizing the key column before the Table.Distinct step. Also filter out or replace null keys, then re-run the grouped version-count query to confirm that each ProductID appears once.