Reputation: 4698
I am having the following query used to retrieve a set of orders:
select count(distinct po.orderid)
from PostOrders po,
ProcessedOrders pro
where pro.state IN ('PENDING','COMPLETED')
and po.comp_code in (3,4)
and pro.orderid = po.orderid
The query returns a result of 4323, and does so fast enough.
But I have to put another condition such that it returns only if it is not present in another table DiscarderOrders for which I add an extra condition to the query:
select count(distinct po.orderid)
from PostOrders po,
ProcessedOrders pro
where pro.state IN ('PENDING','COMPLETED')
and po.comp_code in (3,4)
and pro.orderid = po.orderid
and po.orderid not in (select do.order_id from DiscardedOrders do)
The above query takes a lot of time and just keeps on running. Is there anything I can do to the query such that it executes fast? Or do I need to execute the first query first, and then filter based on the condition by shooting another query?
Upvotes: 1
Views: 706
Reputation: 5782
Same as distinct:
SELECT count(po.orderid)
FROM PostOrders po
WHERE po.comp_code IN (3,4)
AND EXISTS
(
SELECT 1 FROM ProcessedOrders pro
WHERE pro.orderid = po.orderid
AND pro.state IN ('PENDING','COMPLETED')
)
....
/
Upvotes: 0
Reputation: 263693
try using JOIN
than NOT IN
SELECT COUNT(DISTINCT po.orderid) TotalCount
FROM PostOrders po
INNER JOIN ProcessedOrders pro
ON po.orderid = pro.orderid
LEFT JOIN DiscardedOrders do
ON po.orderid = do.orderid
WHERE po.comp_code IN (3,4) AND
pro.state IN ('PENDING','COMPLETED') AND
do.orderid IS NULL
OR NOT EXISTS
SELECT COUNT(DISTINCT po.orderid) TotalCount
FROM PostOrders po
INNER JOIN ProcessedOrders pro
ON po.orderid = pro.orderid
WHERE po.comp_code IN (3,4) AND
pro.state IN ('PENDING','COMPLETED') AND
NOT EXISTS
(
SELECT 1
FROM DiscardedOrders do
WHERE po.orderid = do.orderid
)
Upvotes: 2
Reputation: 9336
You can try to replace:
and po.orderid not in (select do.order_id from DiscardedOrders do)
by
and not exists (select 1 from DiscardedOrders do where do.order_id = po.orderid)
Upvotes: 3