get dbid or database name in sql server

I have seen many times DBA / developers are joining the sysdatabase table in master database to get the database name or database id. There are two builtin sql server functions for this purpose, lets see how to get the database name from dbid or how to get the dbid from database name.

SELECT DB_ID('Database_Name') as [Database ID]

The above T-SQL query is using DB_ID( ) function to get the database id from database name.

SELECT DB_Name(1) as [Database Name]

The second query will give you the database name, the DB_Name ( ) function takes database id as parameter and returns database name.

In both functions if no value is found i.e database name or database id does not exists then a NULL value is returned.


SQL Server DBA

I am a SQL Server DBA with almost 9 years of experience in database technologies.

Right now I am in process of redesigning this website in ASP.NET 2.0 and AJAX. The main purpose of new SQL DBA website is to offer more help to database professionals and make it easy for me to update contents on regular basis.