Hello folks, We have a table with a 150+million records. We need to clear/delete all rows. Delete operation would take forever due to it writing to the t-logs and we cannot change our recovery model for the whole DB. We have tested the truncate table option. What we realized that truncate deallocates pages from the table, and if I am not wrong makes them available for re-use but doesn't shrink the db automatically. So if we want to reduce the DB size, we really would need to do run the shrink db command after truncating the table. Is this normal procedure? Anything we need to be careful or aware about, or are there any better alternatives?
"Delete all rows"... wouldn't DROP TABLE (and re-recreate an empty one with same schema / indices) be preferable ? (I personally like "fresh starts" ;-) )
This said TRUNCATE TABLE is quite OK too, and yes, DBCC SHRINKFILE may be required afterwards if you wish to recover the space.
One thing to remember with Truncate Table (as well as drop table) is going forward this will not work if you ever have foreign keys referencing the table.
truncate
is what you're looking for. If you need to slim down the db afterwards, run a shrink.
This MSDN refernce (if you're talking T-SQL) compares the behind the scenes of deleting rows versus truncating.
Truncating a table is normal procedure, yes. This exact situation is why the keyword was added in the first place.
Depending on the size of the full database, the shrink may take a while; I've found it to go faster if it is shrunk in smaller chunks, rather than trying to get it back all at once.
You have a normal solution(truncate +shrink db) to remove all the records from a table.
As Irwin pointed out. The TRUNCATE command won´t work while being referenced by a Foreign key constraint. So first drop the constraints, truncate the table and recreate the constraints.
If your concerned about performance and this is a regular routine for your system. You might want to look into moving this table to it's own data file, then run shrink only against the target datafile!
Good Luck
As pointed out, if you can't use truncate or drop
SELECT 1
WHILE @@ROWCOUNT <> 0
DELETE TOP (100000) MyTable