How to fix Error 5001 on Windows Server 2025 / Windows 11

Why This Error Happens

Error 5001 with the message “User must be in the master database” typically occurs when a user attempts to execute a system-level command—such as creating or restoring a database, modifying a filegroup, or running certain DBCC operations—while their current session context is pointed to a different database. SQL Server 2025 enforces strict context validation for operations that touch system catalogs, and these commands will fail immediately if the active database context is not master. This is often triggered by connection strings, stored procedures, or scripts that do not explicitly set the database context before executing administrative T-SQL statements.

Step-by-Step Resolution Guide

Step 1: Verify Your Current Database Context

  • Run SELECT DB_NAME(); in your query window to confirm which database is currently active.
  • If the result is not master, this confirms the root cause of Error 5001.
  • Check the dropdown in SQL Server Management Studio (SSMS) toolbar, as it may be pointing to tempdb, model, or a user database.

Step 2: Explicitly Switch Context to Master

  • Add USE master; as the first line in your script before running the command that triggered the error.
  • Example:
  USE master;
  GO
  CREATE DATABASE MyNewDatabase;
  • If using a connection string (ADO.NET, ODBC, or JDBC), ensure the Initial Catalog or Database parameter is explicitly set to master.

Step 3: Update Default Database for the Login

  • Open SSMS and navigate to Security > Logins, right-click the affected login, and select Properties.
  • Under the General tab, check the Default database field and set it to master if administrative tasks are routinely performed under this account.
  • Alternatively, run the following T-SQL command:
  ALTER LOGIN [YourLoginName] WITH DEFAULT_DATABASE = master;

Step 4: Check Application or Script Connection Settings

  • Review any automated jobs, PowerShell scripts, or application connection pools that execute administrative commands.
  • Ensure the connection string or SQL Agent job step explicitly includes USE master; or specifies master as the target database in the job step properties under Run as and Database fields.

Alternative or Verification Steps

  • To verify the fix, re-run the original command (e.g., CREATE DATABASE, sp_configure, or RESTORE DATABASE) and confirm it completes without throwing Error 5001.
  • If the issue persists, check for custom stored procedures or triggers that may be silently switching context via USE statements mid-execution, and audit them using SQL Server Profiler or Extended Events.