In this article, we will show how to write a SQL Query to Get Database Names from SQL Server with an example. It is one of the common Interview Questions that you might face in the interviews.
The below screenshot will show you the list of databases in SQL Server that are available in our current instance.
Get Database Names Example 1
In this example, 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
OUTPUT
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
OUTPUT
Or, use sp_databases stored procedure to get a list of databases in Sql Server. Please refer Interview Questions page.
-- Query to get SQL Server Database Names USE master GO EXEC sp_databases
OUTPUT
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
OUTPUT
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')
OUTPUT