My sql Server 2008 table has more 5 million records. I am deleting more than 4 million records in single statement. It is taking more than an hour. Is this the best query to delete the records?
my delete query
delete From [Table]
where SUBSTRING([Column_YYY],1,CHARINDEX(N'',[Column_YYY])-1) = '4'
No that’s not by any measure the best query. Your substring starts with 1, and you’re comparing against a SINGLE character,
'4'! To use an index on ColumnYYY, just change it to a LIKE clause letting the index quickly hunt down the first two characters.That would be true if that did not target 80% of your table, in which case SQL Server will completely scan the table anyway. To prevent tempdb space issues or overly large transactions (locking), I would have broken it up into bits: