Possible Duplicate:
DELETE Command is too slow in a Table with Clustered Index
I have the following DELETE
query running on my SQL Server 2005 database:
DELETE
pa
FROM
dbo.ProductAttribute pa
INNER JOIN
dbo.Product p ON pa.ProductID = p.ProductID
INNER JOIN
@UpdatedProducts up ON p.ProductID = up.ProductId
LEFT JOIN
dbo.ProductOption pos ON pa.ProductOptionID = pos.StartProductOptionId
LEFT JOIN
dbo.ProductOption pof ON pa.ProductOptionID = pof.FinishProductOptionId
WHERE
p.ProductTypeID = 1
AND
pos.StartProductOptionId IS NULL
AND
pof.FinishProductOptionId IS NULL
This query is taking a long time to execute for my data set (~ 18 minutes).
Here's some context:
@UpdatedProducts
is a table variable with ~90K rows- All of the columns I am joining on are indexed
- The
DELETE
query is affecting ~3K rows
Here are my findings so far:
- Replaced
@UpdatedProducts
with a temp table (due to its size) -- this made little difference. - When I convert the query to a
SELECT
, it runs very quickly (a few seconds). So I'm not sure there is a problem with myJOIN
, as presumably this would run the same way when doing aSELECT
orDELETE
? - There are several
FK
constraints that would need to be validated to allow theDELETE
to succeed -- essentially we need to ensure that there are no more entries indbo.ProductOption
which are referencing the rows we are trying to delete indbo.ProductAttribute
(this is what theIS NULL
checks in theWHERE
clause are checking for). - I looked at the query plan, and the most significant cost is "Clustered Index Delete" with a cost of 59% -- most of the other steps have a cost between 0%-3%.
Any recommendations about how I could speed up this query?