In SQL Server there a couple simple ways to obtain the database id. They are db_id() built in and database_id coulmn from sys.databases view. However there is no guarantee that these two matches in SQL DB. While the database_id filed in sys.databases is consistent and won’t change in the life time of the database, db_id() built in can potentially change after every failover depending on the SQL instance the database ends up on.
Dbid also can be inconsistent between the master and user database. We should not take sys.databases view into account if we want to query other views like sys.dm_exec_Requests, sys.dm_tran_locks or sys.sysprocesses as the dbid used in them is the one represented in db_id() built in.