CodexBloom - Programming Q&A Platform

Performance Issues with MySQL 8.0 and Large JOIN Queries Returning Slow Results

👀 Views: 48 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
mysql performance optimization joins SQL

I've been working on this all day and I tried several approaches but none seem to work. I'm experiencing significant performance issues when executing a large JOIN query in MySQL 8.0. The query involves multiple tables with a considerable amount of data, and while it runs fine on smaller datasets, it takes an excessively long time to return results when the tables grow larger. The specific query I'm trying to optimize looks like this: ```sql SELECT o.order_id, o.customer_id, c.customer_name FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN order_details od ON o.order_id = od.order_id WHERE c.country = 'USA' ORDER BY o.order_date DESC; ``` In my case, the `orders` table has around 1 million rows, the `customers` table has about 500,000 rows, and the `order_details` table has 2 million rows. I've already created indexes on the `customer_id` columns in both `orders` and `customers` tables, as well as on `order_id` in the `order_details` table. However, the query is still taking over 30 seconds to complete. I've tried using the `EXPLAIN` statement to analyze the execution plan, and it shows that the query is performing a full table scan on the `orders` table: ```sql EXPLAIN SELECT o.order_id, o.customer_id, c.customer_name FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN order_details od ON o.order_id = od.order_id WHERE c.country = 'USA' ORDER BY o.order_date DESC; ``` The output indicates that MySQL is using a simple index for the JOIN but still scans a large portion of the `orders` table. I've also looked into the server configuration settings such as `innodb_buffer_pool_size` and `query_cache_size`, but increasing them didn't seem to help much. Additionally, I am using the InnoDB storage engine, and my server is running on a powerful machine with plenty of RAM. Is there a better way to optimize this query or a specific indexing strategy I might be missing? Any insights or suggestions would be greatly appreciated! This is part of a larger API I'm building. Any help would be greatly appreciated! This is my first time working with Sql 3.11. Thanks for your help in advance!