简体   繁体   中英

Performance optimisation for - MS SQL Delete query with NOT IN caluse

I have following SQL query, and it is taking long time to complete. I wanted to check if a different query can be used to achieve the same result, but could also help with performance.

Delete from table1 WHERE fk_id = '1234' AND pk_id NOT IN ('aaaa', 'bbbb', 'cccc');

Note: pk_id is PK column and fk_id is a FK for table1 .

I don't have any suggestions about the query, it's pretty basic.

But you might want to try adding an index:

ALTER TABLE table1 ADD INDEX (fk_id);

With the data you have provided there seems to be no problem with your query as you have used 'AND' condition. Now you need to consider and analyze your database that why is your query taking so much time. So you might want to check out with the following things.

1) select count(1)
from table1
where fk_id = '1234' AND pk_id NOT IN ('aaaa', 'bbbb', 'cccc')
This will give you the count of rows to be deleted.

2) Try something like
SELECT
T.name AS TableName ,O.name TriggerName
FROM sysobjects O
INNER JOIN sys.tables T ON T.object_id = O.parent_obj
WHERE O.type = 'TR' AND T.name = 'table1'

This will tell you the triggers associated with your table.

3) You need to further investigate on the table properties for indexes, any constraints present over there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM