Commit 41372f6e73 for woocommerce

commit 41372f6e731ab08ca73024c3f2c46c7a07c5eb1c
Author: Vladimir Reznichenko <kalessil@gmail.com>
Date:   Wed Feb 4 10:19:13 2026 +0100

    [Performance] Admin: optimize SQL fetching dates for month filter on orders page (#63039)

    Rework the SQL to identify the oldest/newest orders in separate nested SQL queries, rather than scanning the entire table.

diff --git a/plugins/woocommerce/changelog/performance-54579-slow-sql-months-filter b/plugins/woocommerce/changelog/performance-54579-slow-sql-months-filter
new file mode 100644
index 0000000000..b468a102ba
--- /dev/null
+++ b/plugins/woocommerce/changelog/performance-54579-slow-sql-months-filter
@@ -0,0 +1,4 @@
+Significance: minor
+Type: performance
+
+Admin: optimized SQL fetching dates for month filter on orders page
diff --git a/plugins/woocommerce/src/Internal/Admin/Orders/ListTable.php b/plugins/woocommerce/src/Internal/Admin/Orders/ListTable.php
index ded0256241..91cbc74d95 100644
--- a/plugins/woocommerce/src/Internal/Admin/Orders/ListTable.php
+++ b/plugins/woocommerce/src/Internal/Admin/Orders/ListTable.php
@@ -868,21 +868,20 @@ class ListTable extends WP_List_Table {
 	protected function get_months_filter_options(): array {
 		global $wpdb;

-		$orders_table   = esc_sql( OrdersTableDataStore::get_orders_table_name() );
+		$table_name     = OrdersTableDataStore::get_orders_table_name();
 		$min_max_months = $wpdb->get_row(
-			// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is escaped above.
 			$wpdb->prepare(
-				"
-					SELECT MIN( t.date_created_gmt ) as min_date_gmt,
-					       MAX( t.date_created_gmt ) as max_date_gmt
-					FROM `{$orders_table}` t
-					WHERE type = %s
-					AND status != %s
-				",
+				"SELECT MIN(date_created_gmt) as min_date_gmt, MAX(date_created_gmt) as max_date_gmt
+				 FROM (
+					( SELECT date_created_gmt FROM %i WHERE type = %s AND status != 'trash' ORDER BY date_created_gmt DESC LIMIT 1 )
+					UNION ALL
+					( SELECT date_created_gmt FROM %i WHERE type = %s AND status != 'trash' ORDER BY date_created_gmt ASC LIMIT 1 )
+				 ) d",
+				$table_name,
 				$this->order_type,
-				OrderStatus::TRASH
+				$table_name,
+				$this->order_type
 			)
-			// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
 		);

 		/**