To select the full row containing the maximum value of a column within each partition (group) in MySQL, use a window function such as ROW_NUMBER(), RANK(), or DENSE_RANK() with OVER (PARTITION BY … ORDER BY … DESC) inside a Common Table Expression (CTE) or derived table, then filter for rank 1 in the outer query (MySQL 8.0+).
- Standard Pattern: ROW_NUMBER() (One Row per Partition) ROW_NUMBER() guarantees at most one row per partition, even when multiple rows tie for the maximum value.
SQL WITH ranked_orders AS ( SELECT order_id, customer_id, order_date, amount, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY amount DESC, order_id DESC ) AS rn FROM orders ) SELECT order_id, customer_id, order_date, amount FROM ranked_orders WHERE rn = 1 ORDER BY customer_id; PARTITION BY customer_id creates a separate ranking window per customer.
ORDER BY amount DESC, order_id DESC puts the highest amount first and uses order_id DESC as a deterministic tie-breaker.
- Keeping All Tied Rows: RANK() or DENSE_RANK() If two rows in the same partition share the maximum value and you want every tied row returned:
SQL WITH ranked_orders AS ( SELECT order_id, customer_id, order_date, amount, RANK() OVER ( PARTITION BY customer_id ORDER BY amount DESC ) AS rnk FROM orders ) SELECT order_id, customer_id, order_date, amount FROM ranked_orders WHERE rnk = 1 ORDER BY customer_id, order_id; RANK() and DENSE_RANK() both assign 1 to all tied top rows; DENSE_RANK() avoids gaps in subsequent rank numbers if you inspect ranks > 1.
- Alternative Without Window Functions: Correlated Subquery or Derived Table If you want to avoid window sorting or are writing against an older pattern, a correlated subquery or derived table matching (partition_col, max_col) also works (though ties may return multiple rows):
SQL – Correlated subquery approach SELECT o.order_id, o.customer_id, o.order_date, o.amount FROM orders AS o WHERE o.amount = ( SELECT MAX(o2.amount) FROM orders AS o2 WHERE o2.customer_id = o.customer_id ); For very large tables, a composite index on (customer_id, amount) helps correlated subqueries and window partitions alike.
- Operational Checklist Add a deterministic tie-breaker (such as a primary key) in ORDER BY when using ROW_NUMBER() so results do not shift across runs.
Create a composite index on (partition_col, target_col) to speed up partitioning and sorting on large tables.
Avoid SELECT * inside CTEs or subqueries; list only the columns needed downstream.
Check NULL behavior in the ordered column (NULLs sort first or last depending on expression/direction; filter WHERE amount IS NOT NULL if NULLs should not qualify).