Fun part of a developer life is: 'Today what is unknown, tomorrow you know it by learning and doing". And by learning the unknown and implementing you become expert :) I will share something which I learned and develop recently. Long back I got a task to find out used schemas in database where the solution was pretty straight forward. However, this time the task was to get unused schemas. Firstly, I thought this must be fun, never did it but someone must did it so started with google and got some clue but not with proper explanation so thought about writing it.
To find out the solution, you need to go through three tables:
1) Sys.Schemas
2) Sys.database_principals
3) Sys.objects
You know how to find unused schema, now you can delete them if you want.
To find out the solution, you need to go through three tables:
1) Sys.Schemas
2) Sys.database_principals
3) Sys.objects
Easy way to find unused schemas is : If the schema_id from sys.schemas
table is not found in Sys.objects table means those are never used. And both
tables schemas and objects got the column ‘Schema_ID’. Woww!! We know the
solution, yes all most 😊 Why we need database_principals table? When schema name is not specified for those cases we need to use this table. Relations among three tables can be depicted with below diagram:
Fig 1: Relationship among tables |
We covered theory part, let's see in action, below is the SQL code to find out unused schemas in database:
SELECT name
SELECT name
FROM sys.schemas SCH
where SCH.schema_id not between 1 and 4 --This is for dbo, guest, information_schema,sys
and SCH.principal_id not between 16384 and 16399 --- it's related to db_* schema, so don't touch this.
and not exists
( select 1
from sys.database_principals P
where P.default_schema_name=SCH.name ---Name to be used when SQL name does not specify a schema, so we are taking this off
)
and not exists
( select 1
from sys.objects O
where O.[schema_id]=SCH.[schema_id] ---Object uses the schema, so if schema id is not exist in the object; it means the schema is not used.
)
order by SCH.name
You know how to find unused schema, now you can delete them if you want.