The USE Database Statement in SQL Server

The USE [database] command in SQL Server is used to switch the context to a specific database when running queries. This is useful when you need to work with multiple databases or change the active database during a session.

When to use this statement:
– When you want to execute queries on a different database than your default one, without including 3 part identifier (databaseName.schemaName.tableName).
– To switch between databases during a query execution session.

How it Works in SQL Server Management Studio (SSMS):
When you log into SQL Server using SSMS, your database context is automatically set to your default database, which is assigned during the creation of your SQL login.
– If you open a new query window (using the shortcut Ctrl + N), your query will be scoped to the default database.

To change the database context, you can either:
Select the database from the drop-down menu in SSMS.
Run the USE [database] command in your query window.

Use Database Example

-- Use database example sql server
USE [animals];
GO;
Use Database SQL
SQL Use Example

Note: The USE command does not work with Azure SQL Database. Azure SQL uses a different method for database switching, which typically involves connecting to the correct database in the connection string.

If you don’t know the names of the available databases, and they aren’t visible in the SSMS Object Explorer, you can query the sys.databases system catalog view to get a list of all databases.

Hope this was useful info for you. Feel free to browse around, click an internal link you see around you for more random SQL Server DBA tips!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts
Categories
Tags

Always On Availability Groups (AAG) (4) AWS (4) AWS Redshift (6) Certificates & Encryption (3) Change Data Capture (CDC) (2) Database Admin (72) Database Backups & Recovery (14) Database Mirroring (2) Deleting Data (1) Error Messages (5) Git Commands (6) Importing & Exporting Data (2) Linked Servers (3) Linux Admin (2) Logging & Monitoring (1) Measuring Databases (10) Microsoft Patching (2) MySQL (4) Postgres (6) PowerShell Scripts (1) SQL Server Agent (5) SQL Server Database Files (1) SQL Server Data Types (2) SQL Server Management Studio (SSMS) (15) SQL Server Network Connectivity (3) SQL Server on Linux (1) SQL Server Patching (2) SQL Server Performance (6) SQL Server Permissions (2) SQL Server Processes (SPIDs) (7) SQL Server Replication (2) SQL Server Scripts (13) Windows Admin (21) Windows Authentication (2) Windows Automation (1) Windows Events (2) Windows Firewall (4) Windows Subsystem for Linux (WSL) (18)