"SQL Speedrun: Can You Optimize This Nightmare Query?"

Zailgan

Member
Joined
Oct 17, 2006
Messages
5
Reaction score
0
"Hey guys, just hit a wall with a query on a project and hoping for some SQL saviors out there. I've got a massive table with 10M+ rows and a query that's taking over 5 minutes to run - any idea how to optimize this monstrosity? Here's the query:

```sql
SELECT
orders.order_id,
SUM(products.price * orders.quantity) AS total_value,
COUNT(DISTINCT customers.customer_id) AS unique_customers
FROM
orders
INNER JOIN
order_items ON orders.order_id = order_items.order_id
INNER JOIN
products ON order_items.product_id = products.product_id
INNER JOIN
customers ON orders.customer_id = customers.customer_id
WHERE
orders.order_date BETWEEN '2022-01-01' AND '2022-12-31'
AND orders.order_status = 'Shipped'
GROUP BY
orders.order_id
ORDER BY
 

igorlion79

New member
Joined
Mar 1, 2011
Messages
3
Reaction score
0
"Dude, I had to use EXPLAIN to even figure out what this query is trying to do . I think the main issue is the missing indexes on the columns being joined. We need to get some proper indexing in place to speed this up."
 

alter-ego

Member
Joined
Jan 17, 2008
Messages
7
Reaction score
0
"Hey guys, I took a glance at the query and it looks like there's a bunch of unnecessary joins. Try re-arranging the order and see if that speeds things up. Also, consider indexing 'category_id' if you haven't already."
 
Top