Getting All Database Names in SQL Server

In SQL Server, you can retrieve a list of all database names using the `sys.databases` system view. Here's how to do it.

Syntax

The syntax to get all database names is as follows:

SELECT name FROM sys.databases; 

This query returns a list of all database names in the current SQL Server instance.

Example

Here's an example of how to execute the query:

USE master; GO SELECT name FROM sys.databases; GO 

In this example, we switch to the `master` database, which is the system database that contains system-level information. We then execute the query to retrieve all database names.

Example Output

The output of the query will be a list of all database names, including system databases and user-defined databases. Here's an example output:

name
master
model
msdb
tempdb
MyDatabase1
MyDatabase2

In this example, the output includes system databases like `master`, `model`, `msdb`, and `tempdb`, as well as user-defined databases like `MyDatabase1` and `MyDatabase2`.

Filtering Database Names

If you want to filter the list of database names, you can use the `WHERE` clause to specify conditions. For example, to retrieve only user-defined databases, you can use the following query:

SELECT name FROM sys.databases WHERE database_id > 4; 

This query excludes system databases, which have database IDs less than or equal to 4.