Forum Discussion
Adding columns
- 1 year ago
Hi Dicken,
Another interesting approach I could think of was this, thanks
Before Re-Ordering, to add more columns, two functions List.RemoveMatchingItems and List. Accumulate, here's howPost this, follow up with the Re-ordering given below
1. Extracting ColNames and Loading it to Excel
2. Adding a Order Number Column in Excel as per the order you'd like
3. Load this new data back into Power Query (here, that is Col Order)
4. Last stepm using the Order Number col, arrange the data in ascending or descending order5. Just use that query in the Table.ReorderColumns Function
Hi Dicken
Your Power Query (M) script for reordering and standardizing table columns is already quite efficient and idiomatic, especially given the use of Table.ReorderColumns with MissingField.UseNull to handle missing columns gracefully. This approach is beneficial when you want to enforce a consistent column schema across multiple tables, regardless of the input column order or presence.
In terms of simplification, this script is already minimal and readable. You define your expected schema (allcol), and then reorder the columns while automatically inserting any missing ones with nulls. There's no significant way to make it “more efficient” in performance or syntax without sacrificing clarity. One minor change could be directly embedding the allcol list inside the Table.ReorderColumns call to eliminate an extra step, like this:
let
Source = #table(type table [One = Text.Type, Five = Text.Type, Three = Text.Type],
{{"a", "b", "b"}, {"b", "c", "d"}, {"d", "a", "c"}}),
Custom = Table.ReorderColumns(Source, {"One", "Two", "Three", "Four", "Five"}, MissingField.UseNull)
in
Custom
This avoids a variable assignment but functionally behaves the same. Otherwise, your current approach is robust and suitable for use in standardized Power Query workflows, especially when normalizing column layouts for appending or merging tables.