Sub topic 12
Merging Queries to Look Up Related Data
This chapter assumes you can create a query from an Excel table, set data types, and trim text in the Power Query Editor. A merge adds columns from one query to another by matching key values. It works like a join in a database or like XLOOKUP, but it is recorded as a repeatable step.
How a merge works
You pick a main query, a lookup query, and one matching column in each. Power Query compares the key values and returns a new column. That column holds a nested table of the matching rows. You then expand it to choose which columns to keep.
Merging in the editor
- Open the Orders query and choose Home, then Merge Queries.
- Select the CustomerID column in the top table.
- Choose Customers in the second list and select its CustomerID column.
- Pick a join kind. Left Outer keeps every order, even if no customer matches.
- Select OK, then select the expand icon on the new column and tick only the columns you need.
The result is this M code:
let
Merged = Table.NestedJoin(Orders, {"CustomerID"}, Customers, {"CustomerID"}, "Customer", JoinKind.LeftOuter),
Expanded = Table.ExpandTableColumn(Merged, "Customer", {"Name"}, {"CustomerName"})
in
ExpandedOrders and Customers are the names of other queries in the workbook. The last argument of the expand step names the new column, so you can avoid a clash with an existing Name column.
Choosing a join kind
| Join kind | Rows returned | Typical use |
|---|---|---|
| Left Outer | All rows from the first query, plus matches from the second | Looking up details |
| Inner | Only rows that match in both | Keeping valid records only |
| Left Anti | Rows in the first query with no match | Finding orders with unknown customers |
| Full Outer | All rows from both queries | Reconciling two lists |
Common errors
- No matches at all. The key columns have different data types, such as text in one and number in the other. Set both to the same type first.
- Some matches missing. Hidden spaces or different capitalization are the usual cause. Trim and clean text in both key columns. Matching is case-sensitive.
- More rows than before. The lookup query has duplicate keys, so each match creates an extra row. Remove duplicates on the key in the lookup query.
- Nulls after expanding. These are rows with no match. Use a Left Anti merge to list them.
Exercise
A left outer merge of Orders with Customers returns 1,200 rows, but Orders had 1,000. What is the most likely cause, and how do you fix it?
Show answer
The Customers query contains duplicate CustomerID values, so some orders match more than one row. Open Customers, select CustomerID, and use Remove Duplicates (or fix the source data), then refresh the merge.
Exercise
Which join kind lists the orders whose CustomerID does not exist in Customers?
Show answer
Left Anti. It returns only the rows from the first query that have no match in the second.