Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting records with T-SQL efficiently without using IN clause

Is there an efficient way to delete records from SQL Server without using the keyword IN in the below scenario:

-- If Documents were deleted, remove them from your ocean
DELETE FROM IndexHistory 
WHERE DocId IN (SELECT IH.Docid 
                FROM IndexHistory IH 
                LEFT JOIN IndexedLineItems I ON IH.Docid = I.DocId
                WHERE I.Docid IS NULL)

If you study this scenario, you have all the records you want to delete from the query inside the parenthesis.

It is documented fact that using 'IN' is inefficient. So one would think that there should be a way to delete these without the 'IN', because all your records are identify-able without using the "IN".

So for example, I am thinking that something like this might be possible, but I don't have the right syntax:

DELETE FROM IndexHistory IH 
LEFT JOIN IndexedLineItems I ON IH.Docid = I.DocId
WHERE I.Docid IS NULL

I appreciate the answer may still be "no, it's not possible."

If it is not possible, maybe it can be a possible suggestion to improve the language for Microsoft. Before I do that, I thought I would post here to see if I'm missing something.

like image 759
Heap of Pinto Beans Avatar asked Sep 03 '25 03:09

Heap of Pinto Beans


1 Answers

Use not exists:

Delete ih from IndexHistory ih
    where not exists (select 1 from IndexedLineItems ili where ih.Docid = ili.DocId)
like image 117
Gordon Linoff Avatar answered Sep 06 '25 01:09

Gordon Linoff