Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 SQL Server Administration (2005)
 Update Statistics after Truncate table.

Author  Topic 

imrul
Starting Member

36 Posts

Posted - 2010-02-19 : 04:49:32
Hi, can anyone tell me what actually happen with statistics after a table is truncated. Are statistics wiped out or do they sit out there till next update statistics is run? Do update statics have any impact after truncating a table?

Kristen
Test

22859 Posts

Posted - 2010-02-19 : 05:16:28
No. Update statistics only happens when manually invoked (e.g. from a scheduled maintenance task) or it automatic updating of statistics is turned on AND SQL decides that the statistics are stale.

I don't know if truncating a table and then querying it causes SQL to immediately update the stats

Personally I would want to rebuild the stats after some more data had been added / imported into the table. But our housekeeping route would update the stats on that table within 24 hours, so I might leave it at that.
Go to Top of Page

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2010-02-22 : 13:36:03
After truncating, the statistics will be updated next time they are accessed, unless you manually update them.

Consider the following:

Create Table t1 (a int, b char(1), c int);
GO

Declare @i int
set @i = 1
while @i < 10000
begin
insert t1 values(@i, char(@i%65 + 65), @i - 1)
set @i = @i + 1
end
GO

create statistics stT1a on t1 (a);
create statistics stT1b on t1 (b);
GO

dbcc show_statistics ('t1', 'stT1b'); -- 41 rows
GO

Truncate Table t1;
GO
dbcc show_statistics ('t1', 'stT1b'); -- still 41 rows. truncate leaves stats intact
GO

insert t1 values(1, 'a', 0);
GO
dbcc show_statistics ('t1', 'stT1b'); -- still 41 rows, insert doesn't affect them either
GO

SELECT * FROM t1;
GO
dbcc show_statistics ('t1', 'stT1b'); -- still 41 rows (select * doesn't care about stats)
GO

-- now execute a query that will utilize statistics
select * from t1 where b = 'Y';
GO
dbcc show_statistics ('t1', 'stT1b'); -- 1 row (header row only)
GO

drop table t1;
GO
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-02-22 : 14:00:40
Very useful Russell, thanks.
Go to Top of Page

imrul
Starting Member

36 Posts

Posted - 2010-02-23 : 01:30:52
Thanks Kristen and Russel. Helped me a lot.
Go to Top of Page
   

- Advertisement -