Forum Discussion

Dicken's avatar
Dicken
Icon for Post Prodigy rankPost Prodigy
4 months ago
Solved

Table Sort , sort order , comparer

Hi, can someone help with how  power query  sorts / compares  values;   so here i  have combined and sorted two tables; let details = #table( type table [item = text, id = text, num =...
  • pcoley's avatar
    4 months ago

    Power Query's Table.Sort is stable and uses a multi-key comparison, but when you sort only by one column, the relative order of rows with the same value in that column is not guaranteed to preserve the original order from Table.Combine.

    In your example, the "c" rows from the two tables are getting interleaved in a way that feels inconsistent.

    Why this happens

    1. Table.Combine basically appends the rows (it tries to keep the order of the input tables, but it's not a strict guarantee in all cases).
    2. Table.Sort is a stable sort in theory, but in practice when you only specify one column, the M engine compares rows using their internal representation.
    3. When two rows have the exact same value in the sort column (item = "c"), the comparison often falls back to other columns or internal row order, which can produce results that look "random" or different from Excel.

      This is different from Excel, which is usually more predictable with "sort by this column only" while preserving original order for ties.

      How to get predictable / Excel-like behavior

      If you want all rows with the same item grouped together (and within the same item, a predictable order), you should sort by multiple columns:

    let
      details = #table(
        type table [item = text, id = text, num = number], 
        {{"c", "4", 3}, {"c", "3", 3}, {"c", "2", 4}, {"c", "1", 6}}
      ), 
      all = #table(
        type table [item = text, id = text, num = number], 
        {{"a", "", "12"}, {"b", "", "53"}, {"c", "", "55"}, {"d", "", "23"}, {"e", "", "33"}}
      ), 
      Combined = Table.Combine({all, details}), 
      Sorted = Table.Sort(
        Combined, 
        {{"item", Order.Ascending}, {"id", Order.Ascending},  // secondary sort
        {"num", Order.Ascending} // tertiary sort (optional)
        }
      )
    in
      Sorted