Question

I am trying to figure out why the query needs so long, so I can optimize it.

I tried it with EXPLAIN:

EXPLAIN SELECT * FROM (
SELECT p.*, ol. prod_id olpid
FROM products p LEFT JOIN orderlines ol
ON p. prod_id = ol. prod_id ) pol
WHERE pol. olpid IS NULL
ORDER BY category , prod_id;

When I run this on my Workbench, I get the Error Code for Connection lost after 10min (600sec). After I set an Index in Prod_ID, the query answers in roughly a second (perfect), before that, it was nearly impossible to get an answer. Also EXPLAIN PLAN could execute it in a few seconds. Still I want to use EXPLAIN on the Query before using an Index.

Any idea here?

Was it helpful?

Solution

You don't need a subquery here. Use this query instead:

SELECT p.*, ol.prod_id olpid
FROM products p LEFT JOIN orderlines ol
ON p.prod_id = ol.prod_id
WHERE ol.prod_id IS NULL
ORDER BY category, prod_id;

Your initial query takes a longer time to execute because you are using a subquery. The subquery needs to be executed entirely, then the WHERE condition may be applied, and at the end the records are ordered. This is also the reason why your query with EXPLAIN is slow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top