Commit 5c023d6b83a for woocommerce
commit 5c023d6b83abd9343b71042406535022c97b30aa
Author: Vladimir Reznichenko <kalessil@gmail.com>
Date: Tue Jun 2 14:41:18 2026 +0200
[Performance] Optimize \Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableQuery query generation (#65413)
Refactors \Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableQuery to omit GROUP BY when no join is present. Impact is low in terms of timing, but skips unnecessary CPU work for larger data sets.
diff --git a/plugins/woocommerce/changelog/update-47865-orders-table-query-build b/plugins/woocommerce/changelog/update-47865-orders-table-query-build
new file mode 100644
index 00000000000..70befc4cc74
--- /dev/null
+++ b/plugins/woocommerce/changelog/update-47865-orders-table-query-build
@@ -0,0 +1,4 @@
+Significance: minor
+Type: performance
+
+Optimized SQL generation in \Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableQuery by removing 'group by' and 'limit' clauses when they are not required.
diff --git a/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableQuery.php b/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableQuery.php
index 0e46361157b..7b9241f2ada 100644
--- a/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableQuery.php
+++ b/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableQuery.php
@@ -899,6 +899,15 @@ class OrdersTableQuery {
$groupby = $groupby ? ( 'GROUP BY ' . $groupby ) : '';
$orderby = $orderby ? ( 'ORDER BY ' . $orderby ) : '';
+ // Performance note: simplify the query to allow the query optimizer to select a more efficient execution plan. As of
+ // version 10.9, this logic is implemented here as alternative changes above are getting flagged by regression analysis.
+ if ( '' === $join && "{$orders_table}.id" === $fields ) {
+ $groupby = '';
+ }
+ if ( 'LIMIT 0, ' . self::MYSQL_MAX_UNSIGNED_BIGINT === $limits ) {
+ $limits = '';
+ }
+
$this->sql = "SELECT $fields FROM $orders_table $join WHERE $where $groupby $orderby $limits";
if ( ! $this->suppress_filters ) {