SQL Use Database Example

USE Command in SQL Server

USE [database] in SQL Server is a way to change the context to a specific database when you are running a query in Microsoft SQL Server.

When you log into SQL Server using SQL Server Management Studio (SSMS), your database context will be automatically set to your default database which was set during the creation of your SQL login.

This means if you create a new query (SSMS Shortkey: Ctrl + N) in SSMS you’ll automatically be scoped to that database. You can switch context by selecting the drop-down menu in SSMS or by running the USE command:

USE [Database] SQL

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

The USE command does not work with Azure SQL Database.

If you don’t know database names and can’t see them in the Management Studio (SSMS) Object Explorer, try to see if you can query sys.databases (SELECT * FROM sys.databases) to see if anything shows up.

This here is an example of the SQL USE command within a sequence of queries:

SQL Use Example

Another phrase that is used instead of ‘context switching’ is ‘scoping’. For example, this query is database scoped – meaning you should run the query within the context of a specific database.

Comments

2 responses to “USE Command in SQL Server”

  1. […] scope to the desired database before running this […]

  2. […] to Connect to SQL Server with Windows Authentication using a Different Domain, August 25, 2022– USE Command in SQL Server, November 25, 2020– Change Default Database in SQL Server, November 23, 2020– Disk Usage by Top […]

Leave a Reply

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