Sub topic 9
Preparing key columns so rows match
A merge compares key values exactly. If a key looks the same on screen but differs underneath, the row does not match. It silently becomes a null or drops out, depending on the join kind. This chapter covers how to find those mismatches and fix them before you merge.
This chapter assumes you can open the Power Query Editor, load tables as queries, and run a basic merge from Home > Merge Queries. It also assumes you know the common data types (text, whole number, date) and what a left outer join keeps.
What "match" means in a merge
Power Query tests whether the key in the first table equals the key in the second. The comparison is strict in four ways:
- Type: the text
"12"does not equal the number12. - Case:
"ab12"does not equal"AB12". - Spaces:
"AB12 "does not equal"AB12". A non-breaking space (character 160, common in data pasted from web pages) also counts as a different character. - Leading zeros:
"00123"does not equal"123".
Fixing these before the merge costs a few steps. Finding them after a merge usually means working backward from nulls in an expanded column.
Step 1: Make the data types agree
In the Merge dialog, select the key column in each table. Below the previews, Power Query reports something like "The selection matches 8 of 10 rows from the first table." Read this line before you click OK. A low count is the earliest sign of a key problem.
A type mismatch is the most common cause. One query may have read CustomerID as a whole number while the other read it as text because it contains a value such as "C-104". The column header icons show this: 123 for numbers, ABC for text.
Convert both sides to the type that can hold every value. For identifiers, that is nearly always text. Identifiers are labels, not quantities, so you never do arithmetic on them. Text also avoids the loss of leading zeros that happens with numbers.
let
Source = Table.TransformColumnTypes(Orders, {{"CustomerID", type text}})
in
SourceConvert the key in both queries, not just one. If the number is already stored without its leading zeros, converting to text will not bring them back. Step 4 covers that case.
Step 2: Remove spaces and hidden characters
Spaces at the start or end of a value are invisible in the grid, so they are easy to miss. Three functions cover most cases:
| Function | What it removes | Typical source |
|---|---|---|
| `Text.Trim` | Leading and trailing spaces | Manual entry, fixed-width exports |
| `Text.Clean` | Non-printing control characters such as line breaks and tabs | Copy and paste from PDFs or web pages |
| `Text.Replace` with `Character.FromNumber(160)` | Non-breaking spaces | HTML tables, web exports |
Text.Trim does not remove spaces inside a value. "AB 12" stays as it is. If your keys should never contain internal spaces, add Text.Remove(_, {" "}). Only do this when internal spaces are noise in both tables.
You can run these from the interface with Transform > Format > Trim and Clean. Each click adds an applied step. Writing the transformation yourself lets you combine several fixes in one step.
Step 3: Normalize case
Merges are case-sensitive, so convert both key columns to the same case. Transform > Format > UPPERCASE does this, and so does Text.Upper. The choice of upper or lower does not matter as long as both queries use the same one.
The following query is complete and runs as shown. It builds two small tables with messy keys, applies one cleaning function to both, and merges them.
let
Customers = #table(
type table [CustomerID = text, Name = text],
{{" ab12 ", "Ada"}, {"CD34", "Ben"}, {"EF56", "Cy"}}
),
Orders = #table(
type table [CustomerID = text, Amount = number],
{{"AB12", 100}, {"cd34", 50}, {"GH78", 20}}
),
CleanKey = (t as table) as table =>
Table.TransformColumns(
t,
{{"CustomerID", each
if _ = null then null
else Text.Upper(Text.Trim(Text.Clean(Text.Replace(_, Character.FromNumber(160), " ")))),
type text}}
),
Merged = Table.NestedJoin(
CleanKey(Orders), {"CustomerID"},
CleanKey(Customers), {"CustomerID"},
"Customer", JoinKind.LeftOuter
),
Expanded = Table.ExpandTableColumn(Merged, "Customer", {"Name"}, {"Name"})
in
ExpandedWithout CleanKey, none of the three orders would match: " ab12 " has spaces and different case, and "cd34" has different case. With it, the first two orders find Ada and Ben. GH78 has no customer, so its Name is null. That null is correct, because that order has no customer in the table.
The if _ = null then null guard matters. Text functions raise an error on null input, and one error value in a key column can fail the whole refresh.
Step 4: Handle codes with leading zeros
Codes such as 00123 often arrive as numbers in one source and text in another. One query may hold 123 and the other "00123". Convert both to text first, then pad to the known fixed width:
let
Source = #table(
type table [ProductCode = any, Qty = number],
{{123, 5}, {"00456", 2}, {null, 1}}
),
Padded = Table.TransformColumns(
Source,
{{"ProductCode", each
if _ = null then null
else Text.PadStart(Text.From(_), 5, "0"),
type text}}
)
in
PaddedAfter this step both 123 and "00123" become "00123". Padding is only safe when the width is fixed and known. If product codes have mixed lengths, padding creates false matches or misses real ones, so you must understand the source system before applying it.
Keep the original key: use a helper column
The examples above change the key column in place. That is fine when the cleaned value is what you want in the final table. Often it is not. Users may want to see " ab12 " as originally entered, or you may load the table elsewhere.
In that case, add a new column and merge on it instead:
let
Source = #table(type table [CustomerID = text], {{" ab12 "}, {"CD34"}}),
WithKey = Table.AddColumn(
Source, "MatchKey",
each if [CustomerID] = null then null else Text.Upper(Text.Trim([CustomerID])),
type text
)
in
WithKeyDo the same in the other table, merge on MatchKey, and remove the helper column after expanding. The original values stay intact, and the cleaning logic sits in one visible step.
Multiple key columns
When a single column is not unique, such as the same product code sold in several regions, merge on two or more columns. In the Merge dialog, hold Ctrl and click the columns in the same order in both tables. Order matters: the first selected column in the top table pairs with the first selected column in the bottom table, and so on.
Apply every preparation step above to each key column. A row matches only if all key columns match. One column with a trailing space is enough to cause a miss.
Nulls and blank keys
Two things to know about empty keys:
- A truly empty cell is
null. Power Query treats null in one table as matching null in the other, so rows with no key can pair up with each other. This is often unintended. - A cell containing only a space is not null. It is text, and after
Text.Trimit becomes an empty string"", which is still not null. Decide whether to turn""into null with Transform > Replace Values, or to filter such rows out before merging.
Filter out rows with no usable key, or give them a distinct treatment, before the merge. The sections below on row counts and joins cover how to confirm the effect.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Match message reports far fewer rows than expected | Type mismatch between the two key columns | Set both to `type text` |
| A few specific rows stay null after expanding | Hidden space, different case, or a non-breaking space | Trim, clean, replace character 160, then normalize case |
| Codes match for some rows but not others | Leading zeros lost in one source | Convert to text and pad to a fixed width |
| Row count grows after the merge | Duplicate keys in the second table | Check key uniqueness (see the next chapter on verifying a merge) |
| Refresh fails with an error in the key column | A text function applied to null or an error value | Add an `if _ = null` guard |
Cleaning fixes formatting differences. It cannot fix keys that are truly different, such as "Jon Smith" and "John Smith". Those need either a corrected source or fuzzy matching, which a later chapter covers.
Exercise
Orders has CustomerID stored as the number 7 and Customers has it as the text "0007". A merge matches no rows. What two changes make them match, and why can you not just convert the numbers to text?
Show answer
Convert the Orders key to text with Text.From, then pad it to four characters with Text.PadStart(Text.From(_), 4, "0") so 7 becomes "0007". Converting alone gives "7", which still does not equal "0007". Padding is only valid if every code has the same fixed width.
Exercise
A merge on {"Region", "Product"} returns nulls for a few rows even though both tables show the values "North" and "Widget". The data types are both text. Name three problems to check next.
Show answer
Check for trailing or leading spaces (Text.Trim), non-breaking spaces (Text.Replace with Character.FromNumber(160)), and case differences such as "north" versus "North" (Text.Upper on both). Also confirm the key columns were selected in the same order in both tables.