10.5 Merge Queries
Bring related information into a report without losing its meaning
An order export tells you which store handled an order, but the manager's name lives in another table. You could search for each store manually and copy the manager into every order. A saved merge step performs that matching process again when the source tables change, while keeping the matching rule visible.
Power Query Merge connects tables using selected key values. A key is information used to identify the corresponding record, such as Store ID. The result depends on which records you want to retain, how the keys are compared, and how many matching records exist. Understanding those three choices is more useful than memorizing a single Merge button.
All orders, names, stores, rider records and prices in this lesson are fictional. The workflow resembles reporting for a delivery service or a seller using apps such as Swiggy, Blinkit or Amazon, but these examples do not describe any company's real records. Use the small numbers to reason about the operation before applying the same checks to a larger practice file.
1. Understand keys, join kinds and nested matches
One question chooses the tables and direction
Our first question is: keep every order and add its store manager when the directory contains a matching store. Orders therefore belongs on the left, which is the first table selected in the merge dialog. Stores belongs on the right. Left Outer is the join kind that retains the left records while bringing in their right-side matches.
Left and right do not describe where the source worksheets sit on your screen. They describe the two roles in this particular operation. Swapping the tables changes what a left-based join keeps. Read the question and check the selected table names before confirming the dialog.
- The left record: an order whose amount and identifier must remain traceable.
- The right record: a store-directory entry providing the manager detail.
- The key: the Store ID used to find the corresponding directory entry.
- The join kind: the rule deciding which unmatched records are retained.
A merged Table cell contains a set of matches
The graphical merge commonly adds a nested table column. Each cell in that column contains the matching right-side rows for the current left record. It may contain no rows, one row, or several. The word Table in the preview does not by itself mean there is exactly one matching store.
Expansion takes selected fields from those nested matches and displays them as ordinary columns. A one-match lookup gives one output record. Multiple matching right-side rows can create several output records for the same left-side order. That is useful for some intentionally one-to-many relationships, but dangerous if you expected a unique directory lookup.
Merge is different from Append and a first-match lookup
Append stacks compatible records into a longer table. Merge matches related records through keys. A worksheet lookup such as XLOOKUP can retrieve a first matching value; a merge can retain and expand all matching right-side records. Thinking of Merge as merely a faster copied lookup can hide this important difference in result size.
A merge can be appropriate for repeated imports because the preparation and matching steps are saved. It is not automatically faster for every workbook, nor does it make an ambiguous directory correct. Source size, transformations and the load destination all affect the practical design. Start with a clear relationship and measurable controls.
2. Lab 1: prepare the original Orders and Stores
Create two named source Tables
In a new workbook named MergePractice.xlsx, create sheets OrderSource and StoreSource. Enter the following tables at A1 on their respective sheets. Do not include a total record in either data body. Amount contains numeric INR values, and both Store ID fields contain text.
| Order ID | Store ID | Amount |
|---|---|---|
| BLK-1101 | BLK-PUN-01 | 64 |
| AMN-1102 | AMN-SLP-01 | 1299 |
| BLK-1103 | BLK-PUN-09 | 150 |
| Store ID | City Manager |
|---|---|
| BLK-PUN-01 | Abhishek Shinde |
| BLK-PUN-02 | Priyanka Shinde |
| AMN-SLP-01 | Salman |
- Convert OrderSource A1:C4 to an Excel Table using Insert → Table and confirm its header row. Name it
tblMergeOrders. - Convert StoreSource A1:B4 to another Table and name it
tblMergeStores. - Click inside the order Table and choose Data → From Table/Range. Name its query
Orders. - Check Order ID and Store ID are Text and Amount is numeric. Load this staging query as a connection only.
- Import the store Table similarly and name its query
Stores. Keep both fields as Text and load it as a connection only. - Record the independent source controls: three orders totaling ₹1,513 and three distinct nonempty store keys.
The Store ID headings happen to be the same here, but merge keys do not require identical heading names. An Orders field named Store Code could match a Stores field named Store ID when you select the correct pair and their values have compatible types and meaning. Append's heading-alignment rule is a different operation.
Inspect unmatched and unused keys before the merge
Read the three order keys against the directory by hand. BLK-PUN-01 exists and points to Abhishek Shinde. AMN-SLP-01 exists and points to Salman. BLK-PUN-09 is absent. Separately, BLK-PUN-02 exists in the directory but has no order in this tiny source.
- Expected matched order count: two.
- Expected unmatched order count: one.
- Expected amount for matched orders: ₹1,363.
- Expected amount for the unmatched order: ₹150.
- Expected unused directory entry: BLK-PUN-02.
These are predictions, not results copied from a query output. Keeping them beside the workbook helps you notice a wrong table direction or join kind. A report that drops the unmatched ₹150 could still look tidy, but it would no longer represent all three original orders.
3. Merge, count matches, and expand deliberately
Retain every order with Left Outer
Open the query editor and choose Home → Merge Queries → Merge Queries as New. Select Orders as the top table and Stores as the bottom table. Click Store ID in both previews, choose Left Outer, and leave fuzzy matching disabled for this exact-identifier exercise. Confirm the selection and name the new result OrdersWithManager.
The result contains the original order fields and a nested column named Stores. If your editor gives that column another name, use the actual name when following the next expression. Inspect the new column before expanding it. The source order count is still a useful baseline at this stage.
Add a count of matched directory rows
Choose Add Column → Custom Column, name it MatchCount, and enter the following expression. It counts the rows inside the nested Stores table for each order. Set the resulting field to Whole Number. In the clean fixture, expect counts of one, one and zero.
Table.RowCount([Stores])Add another Custom Column called MatchStatus using the next expression. It labels the three cases according to the unique-directory rule. A multiple-match label is an instruction to investigate, not permission to select whichever row appears first.
if [MatchCount] = 0 then "Missing store"
else if [MatchCount] = 1 then "Matched"
else "Multiple store records"- MatchCount zero means the nested set contains no matching store record.
- MatchCount one means the key matched one directory record, regardless of whether its manager detail is filled.
- MatchCount above one means the key found several directory records.
- Keep the original Store ID and Order ID beside these checks.
Expand only the fields the report needs
Click the expand control on Stores and choose City Manager. Keep the column prefix if it helps distinguish source fields; otherwise remove it only when the resulting name is unambiguous. For this simple result, a City Manager field does not collide with an existing order field.
Load the output to a new sheet as a Table named tblOrdersWithManager. The original three orders should remain. The first two have their expected manager names. BLK-1103 remains with no manager value and MatchStatus Missing store. Sum Amount and expect ₹1,513, matching the source total.
Separate a missing key from a missing detail
In a practice copy, clear Salman's City Manager cell while retaining AMN-SLP-01 in the Stores Table. Refresh and inspect the result. AMN-1102 still has MatchCount one, but its manager detail is empty. BLK-1103 still has MatchCount zero because its store key is absent from the directory.
Filtering only empty City Manager values could now mix these two situations. One requires completing a detail for an existing store; the other requires resolving a missing or incorrect store key. MatchCount or an anti join identifies missing matches more precisely. Restore the original manager before continuing the baseline exercises.
4. Demonstrate how duplicate lookup keys inflate totals
Change one right-side key, not every order
Use a separate copy of the workbook. Add a fourth Stores row with Store ID BLK-PUN-01 and City Manager Another Manager. The directory now has two records for the same key, with conflicting details. Refresh OrdersWithManager and inspect MatchCount before looking at the expanded result.
BLK-1101 now has two matches, while AMN-1102 still has one and BLK-1103 has none. Expansion produces four output rows: two copies of the ₹64 order, one ₹1,299 order and one ₹150 unmatched order. Their Amount sum becomes ₹1,577. Only the order whose lookup key has multiple matches is repeated.
- Source orders remain three records totaling ₹1,513.
- Nested matches are two, one and zero.
- Expanded rows become four.
- Expanded Amount becomes ₹1,577, an increase of ₹64.
- The unique-directory assumption has failed even though the query can return data.
Do not remove duplicates on Store ID simply to force the count back down. The two manager names conflict. You need an agreed rule about the current valid record, perhaps supported by an effective date or an authoritative directory correction. An arbitrary survivor would hide the disagreement rather than explain it.
Check directory uniqueness before publishing
Create a reference or duplicate query for directory checks. Group by Store ID and count rows, then inspect keys with counts above one. Keep any invalid or empty keys visible in a separate review list. The aim is to expose the rows needing a decision without silently changing the production directory.
An exact replay of a directory row and two records with different manager details are different problems. Even exact duplicates should be handled with a documented source rule. After the directory is corrected, refresh and verify three rows, ₹1,513 and the intended manager assignments. A corrected total alone does not prove the chosen manager is correct.
Follow a duplicate lookup key
Start with the source order
BLK-1101 carries Amount ₹64 and Store ID BLK-PUN-01.
Find two directory records
The same key appears twice with different manager names. MatchCount becomes two.
Expand both matches
The order's ₹64 amount appears on two output rows, one per matching manager record.
Reconcile and investigate
Total rises from ₹1,513 to ₹1,577. Resolve the directory conflict, then verify the full result again.
Recognize an intentional one-to-many relationship
Some relationships legitimately have several right-side records. An order can have several shipment events, for example. Expanding those events changes the output grain to one row per order-event combination. Repeating the original order amount is then expected structurally, but summing it across event rows would overstate order value.
If the report needs one row per order, summarize the event information appropriately before joining, or use a model designed for separate grains. Choosing the largest or first event without a business definition is not a general solution. State the intended output grain and verify that every measure remains meaningful at that grain.
5. Choose a join kind by the records you need to see
Use separate queries to compare the original fixture
Return to the clean three-order, three-store source. Create separate merge-as-new queries for the alternatives below, so each can be checked against the same unchanged input. Keep the order of tables as Orders first and Stores second unless the instructions explicitly say otherwise.
| Join kind | Records retained | Control |
|---|---|---|
| Left Outer | All three orders, with matching store details | 3 order rows; Amount1513 |
| Inner | Only the two orders with store matches | 2 order rows; Amount1363 |
| Left Anti | The order for BLK-PUN-09 | 1 order row; Amount150 |
| Right Anti | The unused BLK-PUN-02 directory record | 1 store record; no order amount |
| Right Outer | All directory stores and their matching orders | 3 output rows here; known order Amount1363 |
| Full Outer | Matched orders plus unmatched records from either side | 4 output rows here; 3 original orders remain |
The Right Outer and Full Outer counts above depend on this particular fixture's unique keys. They are not fixed formulas for every dataset. A store with several orders contributes several matched combinations. An unused store can contribute a row with no left-side Order ID or Amount, so counting all output rows as orders would be incorrect.
Use anti joins as focused exception reports
Left Anti is useful for finding orders whose Store ID has no directory match. It should return BLK-1103 and ₹150 in this fixture. Right Anti identifies directory entries unused by the current order set, here BLK-PUN-02. For an easier-to-read unused-store report, you can instead place Stores first and Orders second and use Left Anti.
Neither exception necessarily proves a bad record. An unused store might simply have no orders in the selected period. A missing store match might result from a typo, an incomplete directory, a new store or an incorrect scope. The report identifies the question to investigate; it does not decide the answer automatically.
Preserve both keys during full reconciliation
In a Full Outer result, keep the right-side Store ID when expanding, with a clear prefix. An unused directory store has no left-side order key, so the right-side key is the evidence you need to identify it. Dropping it can leave a row with a manager name but no visible explanation of which store it belongs to.
Separate rows into matched, order-only and directory-only categories before summarizing. For the clean fixture, there are two matched order rows, one order-only row and one directory-only row. The original order amounts still total ₹1,513, while the directory-only row has no recorded order amount. Missing is not the same as a recorded zero order.
6. Lab 2: match rider details and test a directory update
Prepare a complete small delivery example
The original lesson also introduced Orders joined to Riders. This lab gives that idea a complete fixture. On new sheets, create the following Tables and name them tblRiderOrders and tblRiders. They are separate from the store-manager exercise. Each order has one assigned rider identifier, and this directory is intended to have one current record per rider.
| OrderID | RiderID | Amount |
|---|---|---|
| R-101 | R1 | 210 |
| R-102 | R1 | 420 |
| R-103 | R2 | 315 |
| R-104 | RX | 105 |
| RiderID | RiderName | City |
|---|---|---|
| R1 | Asha | Pune |
| R2 | Nikhil | Nashik |
| R3 | Meera | Mumbai |
- Import the two Tables as staging queries RiderOrders and Riders. Set RiderID to Text in both and Amount to a suitable numeric type.
- Create Merge Queries as New with RiderOrders first and Riders second. Select RiderID on each side and Left Outer.
- Name the result
OrdersWithCity. Add a MatchCount custom column usingTable.RowCount([Riders])before expanding. - Expand RiderName and City. Retain RiderID, OrderID, Amount and MatchCount in the output.
- Load the result and check four orders totaling ₹1,050. The known matches represent three orders totaling ₹945.
- Check Pune has two matched orders totaling ₹630, Nashik has one totaling ₹315, and RX remains an unmatched ₹105 order.
R1 appears twice in the order table because one rider handled two orders. That repetition is expected on the left. The uniqueness requirement for this lookup applies to the right-side rider directory. Confusing repeated transactions with repeated directory keys can cause students to delete valid orders before they even start matching.
Change a detail while keeping the key stable
In a copy, change R1's City from Pune to Mumbai in the source Riders Table. Save the source and refresh the dependent query. Both R1 orders should now show Mumbai. The matched city subtotal of ₹630 moves from Pune to Mumbai, while total orders remain four and total Amount remains ₹1,050.
This describes a current-directory lookup. It does not preserve historical rider locations. If a real report asks which city a rider belonged to when an older order occurred, a directory containing only today's city is insufficient. The project would need historical effective dates and a suitable matching rule. A successful refresh cannot invent that missing history.
Resolve the missing rider explicitly
After restoring the baseline, add an approved fictional directory row RX, Isha, Solapur. Refresh and expect all four orders to have one match, with the ₹105 amount now assigned to Solapur. The total remains ₹1,050 because you added descriptive information, not a new order. The unused R3 entry remains a separate directory-coverage observation.
Keep before-and-after controls for both changes. An updated city should affect classification, while adding a valid directory record should affect match coverage. Neither should change the underlying source order amounts. If those totals move, inspect whether the update introduced duplicate keys or whether the source orders changed at the same time.
7. Lab 3: match prices using City and Product together
A product can have different prices in different cities
Create a third independent practice example. The three rows below represent requested product quantities, and the directory defines a price for each city-and-product pair. All prices are fictional INR unit prices for the same practice date. No discounts or taxes are applied in this example.
| City | Product | Quantity |
|---|---|---|
| Pune | Rice | 2 |
| Nashik | Rice | 3 |
| Pune | Milk | 4 |
| City | Product | UnitPrice |
|---|---|---|
| Pune | Rice | 50 |
| Nashik | Rice | 55 |
| Pune | Milk | 30 |
- Convert the ranges into named Tables and import them as queries PriceOrders and CityPrices.
- Set City and Product to Text in both. Check each pair occurs once in the price directory.
- Create a Left Outer merge with PriceOrders first. Select City, then hold Ctrl and select Product in the left preview.
- Select City and then Product in the same order in the right preview. The small selection numbers should pair City with City and Product with Product.
- Check one nested match for every order, then expand UnitPrice.
- Add LineValue using
[Quantity] * [UnitPrice]. Expect ₹100, ₹165 and ₹120, totaling ₹385.
Selecting Product alone would be ambiguous for Rice because there are two city-specific prices. In a test copy, that incorrect merge expands to five rows. The two Rice requests each match both prices. Calculated LineValue then totals ₹645: 100 plus 110 plus 150 plus 165 plus 120. This is a wrong result produced by a valid but incomplete matching rule.
Keep the key parts separate
Using multiple selected columns avoids inventing an ambiguous concatenated key. Simply joining text without a separator can make different pairs look identical: AB plus C and A plus BC both become ABC. Even a separator needs an escaping rule if it can appear inside values. The native multi-column selection expresses the relationship directly.
Column selection order matters because the first selected key on one side is paired with the first selected key on the other. Selecting City then Product on the left but Product then City on the right asks a different question. For our labels that gives no intended matches. Check the numbered selections before accepting the dialog.
Add period only when the price definition requires it
If a directory contains different prices for different months, City and Product may no longer be unique. A period or effective-date rule becomes part of the relationship. Do not remove the older record merely to make the key unique unless the report explicitly asks for current prices only. The needed key follows the business question.
Similarly, a matched row with an empty UnitPrice is not a missing key. MatchCount can equal one while the required measure is absent. Keep a separate value-quality check before calculating LineValue. A valid-looking multiplication result should not be used to disguise an unknown price as a free item.
8. Prepare keys without changing their identity
Types, spaces and letter case need a policy
Use compatible types on both sides. Store codes such as 0012 are usually identifiers, so preserve their text representation before an automatic numeric conversion removes leading zeros. Changing the resulting number 12 back to Text does not recover whether the original code contained two, three or four leading zeros.
- Inspect raw keys before standardizing them.
- Trim surrounding spaces only when the source definition says those spaces are accidental.
- Choose a consistent letter-case policy only when case does not distinguish different identifiers.
- Apply the same justified normalization to both sides.
- Check whether normalization creates collisions between previously different keys.
For city aliases, a small approved mapping table can be more transparent than repeated text replacements. Keep the raw city and a normalized matching field separately. An alias such as an agreed old and new city name can then be reviewed and updated centrally. Do not assume two similar personal names identify the same person.
Missing keys are a separate input problem
Validate empty, null and whitespace-only identifiers before matching. Do not rely on assumptions copied from a database's null behavior, and do not use a shared blank directory key as a catch-all identity. An order with no Store ID needs an explicit missing-key status, even if another table also contains an empty value.
In a larger workflow, separate invalid-key orders for review, merge the valid-key orders, and retain the invalid records with their source identity and an explicit status in the final reporting design. If you later append those review records back, align their fields deliberately and reconcile the total original order count and amount. Filtering invalid records away without accounting for them would make coverage look better than it is.
Trace an unexpected result through the recorded steps
When the final report is wrong, compare the queries at specific stages. First inspect the raw source keys. Next inspect the normalized keys, then the nested match counts, and finally the expanded fields. This sequence separates a source problem from a matching problem and an expansion problem. Changing several steps together makes it harder to identify the cause.
For example, three correct source orders can become three nested records and four expanded rows. That points toward multiple matches during expansion. If the Orders staging query already has four records, investigate that earlier source or append step instead. If row counts stay correct but the wrong manager appears, inspect the chosen key, normalization collisions and directory content.
After an external file changes, confirm the imported staging query contains the new value before judging the merge. A stale source, blocked connection or failed refresh can leave an old-looking result even when the join logic is correct. Keep the last verified source controls and show unresolved refresh errors clearly. An updated timestamp alone does not prove that the intended values reached the final report.
Fuzzy matching suggests candidates
Fuzzy merge is intended for similar text values where supported. It can help suggest that two messy labels might refer to the same category. It should not be treated as proof that Rahul and Rahul P are the same rider, or that two nearly identical store codes represent the same business location.
Review a small labeled sample, understand the options available in your Excel version, and retain the original values and accepted mapping. A similarity threshold is not a verified probability of identity. For the exact Store ID and RiderID labs here, leave fuzzy matching off and investigate mismatches through the source records.
9. Original practice themes with complete answer guidance
The following tasks extend the original Merge practice list. Use the appropriate fixture for each question and reset deliberate faults before comparing results. The aim is to explain the relationship and its checks, not simply to reproduce a particular screenshot.
1. Merge Orders to Riders using Left Outer
Use RiderOrders first and Riders second, select RiderID on both sides, and retain every order. Before expansion, count nested matches. The baseline output has four orders totaling ₹1,050, including RX as an unmatched ₹105 order. This preserves the source coverage while adding available details.
2. Show only the matching rider orders
Create a separate Inner merge using the same key pair. It returns R-101, R-102 and R-103, totaling ₹945. R-104 disappears because RX is absent from the baseline directory. Label this as a matched-only result rather than reporting it as all source orders.
3. Expand City and RiderName
Select those fields from the nested Riders column. Keep the left RiderID and the MatchCount check. You do not need another identical RiderID field for this simple left lookup. Retain prefixes when the source already has a City or RiderName field that would otherwise become ambiguous.
4. Find missing rider references with Left Anti
Use RiderOrders first and Riders second with Left Anti. The baseline result is R-104, RiderID RX, Amount ₹105. This finds an absent match. It is more precise than filtering empty City, because an existing matched rider could also have an incomplete city detail.
5. Match a Berlin product-price table by SKU
For a separate fictional euro example, use order SKU DE-01 with Quantity2 and a unique price directory entry DE-01 with UnitPrice8. A checked left lookup gives LineValue €16. Keep the currency and price date explicit. If the directory has several prices for that SKU, add the required key or effective-date rule before calculating.
6. Explain choosing Merge for a large repeated report
A saved query can centralize source preparation and bring several related fields into a refreshable result. That is a maintainability benefit for repeated reporting. It does not guarantee speed or uniqueness. Compare the actual workload and keep match counts, exceptions and amount reconciliation regardless of the number of rows.
7. Change a rider city and refresh
Change R1 from Pune to Mumbai in a test copy of the source directory. Both R1 orders should change city, moving ₹630 between city groups while the overall ₹1,050 remains unchanged. Observe refresh completion and verify the details. This is a current-directory result, not an automatic historical assignment.
8. Merge using City and Product
Select City then Product on both sides of the price lab. The correct line values are ₹100, ₹165 and ₹120. Product alone gives multiple Rice matches and the incorrect ₹645 total. The complete key identifies the relevant price; the fact that each partial match is a valid directory row does not make it appropriate.
9. Review almost-matching names
Use fuzzy matching only as a candidate-review exercise on fictional text, where the feature is supported. Keep Rahul and Rahul P separate until an agreed source confirms their identity. Record accepted mappings rather than lowering a threshold until all rows appear matched. Exact identifier joins should remain exact.
10. Keep a separate OrdersWithCity query
Choose Merge Queries as New and give the result a descriptive name. This leaves the source query outputs independently inspectable. The new query still depends on them and can change on refresh; it is not a frozen snapshot of their current values.
11. Apply a clearly fictional conversion assumption
The original practice used a hypothetical rate of ₹105 per £1. Under that stated classroom assumption only, ₹315 divided by105 equals £3. Name the rate and its units explicitly, retain the original amount, and do not present105 as a current exchange rate. A merge operation does not itself establish a conversion policy.
12. Document the join step for a teammate
Add a clear description to the merge step where the editor supports step properties. Record the left and right queries, key columns in order, join kind, expected uniqueness and exception handling. Include the source row and amount controls so another student can detect a changed relationship after refresh.
10. Interview questions and checks to remember
Does Left Outer always preserve the same number of rows after expansion?
No. It retains left records, but multiple right-side matches can expand a left record into several rows. In the store fault test, the source's three orders become four output rows because one order matches two store records. Check MatchCount and the final output grain before summing repeated measures.
Why is an empty manager not enough to identify an unmatched store?
The key may match a directory record whose manager detail is empty. MatchCount distinguishes no matching record from a matched record with missing attributes. Those cases need different repairs, so retain both match status and required-detail checks.
Which duplicate keys are expected in the rider exercise?
R1 appears in two orders, which is expected because the rider handled two separate transactions. The directory should have one current R1 record for this lookup. Repetition on the transaction side and ambiguity on the directory side are different conditions.
Can matching column names replace selecting the correct keys?
No. Merge uses the key columns you explicitly select, and their headings may differ. Verify their values, types and business meaning. For multiple keys, verify selection order. Append aligns headings automatically, but that is a separate operation with a different purpose.
What should you check after changing the directory?
Check the intended attribute change, match counts, unresolved exceptions, source order identities, output row count and amount total. A directory correction should not unexpectedly add or remove order value. If it does, inspect duplicate keys, join kind and concurrent source changes.
11. Revision cards and continued practice
- Start with the retained records. The business question determines the left table and join kind.
- Count nested matches. Zero, one and many are different states.
- Expansion can repeat measures. Check the output grain before summing.
- Use the complete key. City plus Product can identify a price when Product alone cannot.
- Missing detail differs from missing match. Keep separate checks for each.
- Reconcile after refresh. Counts, keys, amounts and assignments support different conclusions.
Keep the original downloadable cards for quick revision: Merge concept card, Left Outer and Inner card, and Expansion card. Use this lesson's detailed checks when practicing beyond the compact cards.
The Excel Task Hub includes additional exercises, including a separate messy-order cleaning dataset. Keep its values and currency separate from these merge fixtures. A repeated order identifier in any supplementary exercise still needs an identity rule before removal; it is not automatically a duplicate transaction.