CodexBloom - Programming Q&A Platform

MySQL 8.0 - Unexplained Query Performance Degradation with CTEs in Subqueries

👀 Views: 113 💬 Answers: 1 📅 Created: 2025-06-27
mysql performance cte SQL

I'm a bit lost with I'm sure I'm missing something obvious here, but I'm experiencing a important performance degradation when executing queries that involve Common Table Expressions (CTEs) in MySQL 8.0. I have a query that looks like this: ```sql WITH sales_data AS ( SELECT product_id, SUM(quantity) as total_sold FROM sales GROUP BY product_id ) SELECT p.product_name, sd.total_sold FROM products p JOIN sales_data sd ON p.id = sd.product_id WHERE sd.total_sold > 100; ``` On execution, the query takes around 15 seconds to complete, while a similar query without the CTE runs in under 2 seconds. I noticed that the execution plan shows a full table scan on the `sales` table when using the CTE, whereas the other version uses an index on `product_id` effectively. I've tried rewriting the query without the CTE, and it performs much better: ```sql SELECT p.product_name, SUM(s.quantity) AS total_sold FROM products p JOIN sales s ON p.id = s.product_id GROUP BY p.product_name HAVING total_sold > 100; ``` I also checked my MySQL configuration. Here are some relevant settings: - `innodb_buffer_pool_size` is set to 1G - `query_cache_size` is disabled - `tmp_table_size` is set to 64M Could this be a bug in MySQL 8.0, or am I missing something? I’ve read that CTEs may not be optimized the same way as derived tables in MySQL. How can I improve the performance of my CTE-based query? Any insight or recommendations on how to approach this scenario would be greatly appreciated! Any help would be greatly appreciated!