SELECT
RES.NUM_PROCESS,
RES.ID_SYSTEM
FROM
RESTRICTED_PRECESS RES
WHERE
RES.ID_SYSTEM <> 'CYFV'
AND NOT Exists ( SELECT 1 FROM PRECESS PR
WHERE PR.ID_SYSTEM = RES.ID_SYSTEM
and RES.NUM_PROCESS and PR.NUM_PROCESS
)
Slow query
Hello everyone
I have the following query that is taking more than 1 hour to run.
SELECT
RES.NUM_PROCESS,
RES.ID_SYSTEM
FROM
RESTRICTED_PRECESS RES
WHERE
RES.ID_SYSTEM <> 'CYFV'
AND RES.NUM_PROCESS NOT IN
(
SELECT PR.NUM_PROCESS
FROM PRECESS PR
WHERE PR.ID_SYSTEM = RES.ID_SYSTEM
)
Can someone tell me how I do this query with NOT EXISTS
Thank you
4 answers
Sort by: Most helpful
-
Jingyang Li 5,891 Reputation points
2020-08-26T17:46:49.357+00:00 -
Guoxiong 8,206 Reputation points
2020-08-26T18:26:04.657+00:00 You can try INNER JOIN instead:
SELECT RES.NUM_PROCESS, RES.ID_SYSTEM FROM RESTRICTED_PRECESS RES INNER JOIN PRECESS PR ON PR.ID_SYSTEM = RES.ID_SYSTEM AND PR.NUM_PROCESS <> RES.NUM_PROCESS WHERE RES.ID_SYSTEM <> 'CYFV';
-
Viorel 117.6K Reputation points
2020-08-26T19:02:25.403+00:00 Check if it has sense to try this too:
SELECT NUM_PROCESS, ID_SYSTEM FROM RESTRICTED_PRECESS WHERE ID_SYSTEM <> 'CYFV' EXCEPT SELECT NUM_PROCESS, ID_SYSTEM FROM PRECESS
-
MelissaMa-MSFT 24,201 Reputation points
2020-08-27T02:30:49.483+00:00 Hi @Edgar Toia Neto ,
A small modification on Jingyang's query as below:
SELECT RES.NUM_PROCESS, RES.ID_SYSTEM FROM RESTRICTED_PRECESS RES WHERE RES.ID_SYSTEM <> 'CYFV' AND NOT Exists ( SELECT 1 FROM PRECESS PR WHERE PR.ID_SYSTEM = RES.ID_SYSTEM and RES.NUM_PROCESS = PR.NUM_PROCESS )
If we change one query from 'NOT IN' to 'NOT EXISTS', we need to add one condition which is 'RES.NUM_PROCESS = PR.NUM_PROCESS' in your situation.
In addition, you could also have a try with 'LEFT JOIN'. In some situation, it could be faster than others.
SELECT RES.NUM_PROCESS, RES.ID_SYSTEM FROM RESTRICTED_PRECESS RES LEFT JOIN PRECESS PR ON PR.ID_SYSTEM = RES.ID_SYSTEM WHERE RES.ID_SYSTEM <> 'CYFV' AND RES.NUM_PROCESS<>PR.NUM_PROCESS
'EXCEPT' is also a good solution but you need to consider whether it is needed to exclude the NULL values during the query.
Besides, it is recommeded to create some indexes on columns 'ID_SYSTEM' and 'NUM_PROCESS' on both tables.
If the response is helpful, please click "Accept Answer" and upvote it.
Best regards
Melissa