Get Database Names from SQL Server

In this article, we will show how to write a SQL Query to Get Database Names from SQL Server with an example. The list of databases in SQL Server that are available in our current instance.

Get Database Names from SQL Server 1

Get Database Names Example 1

Here, we will show you how to Get database names in Sql Server

-- Query to get SQL Server Database Names
USE master
GO
SELECT name FROM sys.databases
Get Database Names from SQL Server 2

You can also use sysdatabases to get the list of databases in SQL Server.

-- Query to get SQL Server Database Names
USE master
GO
SELECT name FROM sysdatabases
Get Database Names from SQL Server 3

Or, use sp_databases stored procedure to get a list of databases in Sql Server.

-- Query to get SQL Server Database Names
USE master
GO
EXEC sp_databases
Get Database Names from SQL Server 4

Get Database Names Example 2

In this example, we will restrict the result. I mean, we will get Database names in a Server without system databases. If you know the database id, use the following query to display the list of databases except for system databases

-- Query to get SQL Server Database Names
USE master
GO
SELECT database_id, name FROM sys.databases
WHERE database_id > 4
Get Database Names from SQL Server 5

Or, try NOT IN operator

-- Query to get SQL Database Names
USE master
GO
SELECT database_id, name FROM sys.databases
WHERE name NOT IN ('master', 'model', 'msdb', 'tempdb')
Get Database Names from SQL Server 6