Sub topic 2
Appending and Merging Queries
Assume you know Excel tables, basic Power Query steps, column data types, and the purpose of a lookup. In Power Query, append stacks rows. Merge matches rows and adds columns.
Appending Three or More Queries
Use Append Queries as New when several queries contain similar records, such as monthly sales tables.
In the dialog:
- Select Three or more tables.
- Move the required queries into the tables to append list.
- Select OK.
Power Query creates a new query and leaves the source queries unchanged. The same operation in M uses Table.Combine:
let
Source = Table.Combine({Sales_January, Sales_February, Sales_March})
in
SourcePower Query matches appended columns by name, not by position. If a query lacks a column, its rows receive null. Columns with different names remain separate columns. Check that related columns also have compatible data types.
Merging Two Queries on a Key Column
Use Merge Queries when one table contains attributes needed by another table. For example, merge Orders with Customers using CustomerID.
let
Source = Table.NestedJoin(
Orders,
{"CustomerID"},
Customers,
{"CustomerID"},
"Customers",
JoinKind.LeftOuter
),
Expanded = Table.ExpandTableColumn(
Source,
"Customers",
{"Name", "Region"},
{"Name", "Region"}
)
in
ExpandedThe merge first creates a nested table column. Expanding that column adds selected fields to the order rows. A customer key should usually be unique in Customers. Duplicate keys there can create multiple output rows for one order.
Join Kinds and the Rows Each One Keeps
The join kind controls which unmatched rows remain.
| Join kind | Rows kept |
|---|---|
| Left outer | Every row from the first table; matching rows from the second |
| Right outer | Every row from the second table; matching rows from the first |
| Full outer | Every row from both tables |
| Inner | Only rows with a match in both tables |
| Left anti | Rows from the first table with no match |
| Right anti | Rows from the second table with no match |
Use an anti join to find missing relationships, such as customers with no orders.
Preparing Key Columns So Rows Match
Before merging, make both key columns the same data type. Clean text keys with Text.Trim and Text.Upper:
let
Cleaned = Table.TransformColumns(
Customers,
{{"CustomerID", each Text.Upper(Text.Trim(_)), type text}}
)
in
CleanedFor composite keys, select the same columns in the same logical order on both sides. Check for nulls, accidental spaces, and duplicate keys before expanding.
Exercise
Which operation should combine January, February, and March sales into one table?
Show answer
Append the three queries. Use a merge only when rows must be matched to add columns.