0

I have a pretty big temp table (~5 million rows) that I need to update a few fields on.

Here's an example update statement:

UPDATE T    
SET CarModel = 
    CASE 
        WHEN CarModel = '350z' AND ModelYear = 2008 AND CarMake NOT LIKE '%DATSUN%' THEN '370z Nismo' 
        ELSE CarModel
    END,
IsMidTierCar = 
    CASE 
        WHEN NumberOfCarsSold >= 500000 AND <= 1000000 THEN IsMidTierCar 
        ELSE NULL 
    END,
IsRareCarMakeModel = 
    CASE 
        WHEN CarModel = '350z' AND SpecialEditioName != '' AND ModelYear = 2008 THEN 1
        ELSE 0
    END
FROM #CarsTempTable AS T
WHERE IsRareCarMakeModel IS NULL

The catch is the IsRareCarMakeModel field is NULL for every single row in the temp table before this update runs. Right now the fastest time I see it run in is when I don't create any index on my temp table. Any other index combination I've tried runs in at least 5x as long (and usually I just end up killing it instead of waiting for it to finish.)

Is no index going to be the best I'll ever get because of the cardinality of the temp table's IsRareCarMakeModel field is extremely low therefor a table scan is always going to be the best course of action for the optimizer?

2
  • If every single row is null, why are you checking that on the where clause? Do you execute that update more than once before dropping that temp table? Could you add the execution plan to your question? Since it's about performance I believe it might be useful.
    – Ronaldo
    Commented Nov 22, 2019 at 20:25
  • I do realize in my scenario it's redundant and not needed, but I think also theoretically ineffectual in regards to my question. In other words, even without the WHERE clause there, a table scan would still ultimately need to happen and I'm guessing no index would help me in that case?
    – J.D.
    Commented Nov 22, 2019 at 20:28

1 Answer 1

1

Ronaldo's comment got me thinking and the more I think about it, I would answer my own question as: if every row of a table needs to be read, then there is no way to order the way that data is stored in order to improve the read performance. In other words, there's no index that would make the update statement in my scenario any faster because every row needs to be read to be updated in that query (regardless of the fact that the query has a filter because the filter doesn't actually return any less rows than everything in the table.)

1
  • 1
    One extra point: Index creation requires a table scan in first place. Indexes are beneficial only when you are going to search the same column(s) more than once.
    – Alex
    Commented Nov 25, 2019 at 1:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.