Tuesday 4 September 2018

Simple Simple SQL Query Does Not Work

I have a relatively simple query which usually takes no longer than about 10 seconds to return. It is as follows:

SELECT personid
FROM vw_has_copyright
WHERE (Orderid IN (SELECT orderid
                   FROM orders WHERE eventid = 1234))
GROUP BY personid
ORDER BY personid

Now it just hangs when I run this query. If I run select orders.orderid from orders where orders.eventid = 1234 - and then use the list generated from this query with the select personid from vw_has_copyright where Orderid in (*my list here...*) it works fine.
So why is it no longer working with the nested select query? It seems so strange but I'm not sure how to go about debugging it? Thanks in advance!!
---EDIT---
Rather embarassingly, the problem was that I haven't been maintaining my indexes properly. Due to high fragmentation on my orders table indexes the query suddenly stopped working, however after rebuilding and reorganising them the query now works again! Moral of the story - look after your database!!

IN is very tricky, specially on a orders table that usually have a huge amount of records. I suggest changing it to EXISTS or even a regular join.
Here is a very good link that explains the difference between these 3 operands

0 comments:

Post a Comment