Skip to content

Removing duplicate rows

Removing duplicates in Power Query keeps the first row it meets for each key. This page shows how to keep the last row instead, which is what is usually wanted when the last row is the most recent.

The table below lists sales orders for three customers. The aim is to keep one row per customer, which should be the customer’s most recent order. The rows that should survive are outlined in red:

An Excel table of orders with Product Key, Order Date, Customer Key, Sales Territory and SalesOrderNumber, where the latest order for each of customers 100, 101 and 102 is outlined in red

The obvious approach looks simple:

  • Sort the table by Order Date, newest first.
  • Select the Customer Key column and choose Remove Duplicates.

The result, however, is wrong. Although the Sorted Rows step sorted the dates in descending order, the rows that remain are each customer’s earliest order rather than the latest:

The query after Remove Duplicates, showing the orders dated 03/05/2020, 02/04/2020 and 04/03/2020 for customers 102, 101 and 100, with the Applied Steps Source, Changed Type, Sorted Rows and Removed Duplicates

Power Query does not run each step in full and in order. It works out what the final step needs and evaluates only that, which is known as lazy evaluation, so it is free to rearrange or skip work that a later step does not depend on. Remove Duplicates, which is the Table.Distinct function, does not promise to respect the order that an earlier step set, so the engine can pick which duplicate to keep without regard to the sort.

Table.Buffer loads a whole table into memory and holds it there, which forces the sort to run in full before the next step reads it. Later steps then see the rows in the sorted order, so Remove Duplicates keeps the newest order for each customer.

To apply it, wrap the formula in the Sorted Rows step in Table.Buffer:

= Table.Buffer(Table.Sort(#"Changed Type",{{"Order Date", Order.Descending}}))

The query now returns the right rows, which match the ones outlined in the original table:

The query result sorted by Customer Key, showing the orders dated 29/03/2020, 27/04/2020 and 27/05/2020 for customers 100, 101 and 102