Friday, 5 May 2017

How to find size of databases and last time they got accessed

Sometimes you may need to free some space on MSSQL server and idetify databases which are not used long time back. This is especially useful on development servers where people may restore database just for troubleshooting of some issues and then the database is not needed anymore!

with fs
as
(
    select database_id, type, size * 8.0 / 1024 size
    from sys.master_files
)

select db.*, last_user_seek = MAX(last_user_seek),
 last_user_scan = MAX(last_user_scan),
 last_user_lookup = MAX(last_user_lookup),
 last_user_update = MAX(last_user_update)
from (
 select 
  name,
  (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,
  (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB 
 from sys.databases db
) as db
left join sys.dm_db_index_usage_stats stats on stats.database_id = db_id(db.name)
group by db.name, db.DataFileSizeMB, db.LogFileSizeMB
order by db.DataFileSizeMB desc

References:
Sql server 2008 howto query all databases sizes
How do you find the last time a database was accessed