How to Get the Name of a Current Database in PostgreSQL

While working with the PostgreSQL database, identifying the database name is an important task as it enables us to access and manage that particular database. For this purpose, PostgreSQL offers a couple of methods, such as CURRENT_CATALOG, and CURRENT_DATABASE. Moreover, users can get a list of all databases using different commands and metacommands.

This post illustrates how to get the name of the current database using the following content:

- Method 1: Using CURRENT_CATALOG
- Method 2: Using CURRENT_DATABASE
- Bonus Tip: Get All Databases’ Names

How to Get Current Database Name in PostgreSQL Using CURRENT_CATALOG?

In SQL standard database management systems, databases are commonly known as “catalogs”. To get the name of current catalogs/databases, the CURRENT_CATALOG function is used in PostgreSQL. It doesn’t accept any argument and can be executed without parenthesis, as shown in the following example:

SELECT CURRENT_CATALOG;
img

How to Get Current Database Name in PostgreSQL Using CURRENT_DATABASE?

Alternatively, the CURRENT_DATABASE function can be utilized in PostgreSQL to get the name of current catalogs/databases. It doesn’t accept any argument and must be executed with parenthesis, as depicted in the following example:

SELECT CURRENT_DATABASE();
img

Bonus Tip: How to Get All Databases’ Names in Postgres

Execute the “\l” meta-command to list all the databases’ names along with their attributes/details, such as database name, owner, etc.

\l
img

That’s all about getting the names of the current or all databases in PostgreSQL.

Conclusion

In Postgres, a couple of built-in methods, such as CURRENT_CATALOG, and CURRENT_DATABASE are used to get the names of the current database. Moreover, users can get the names of all databases using different commands and metacommands. This post has presented different methods to get the names of current or all databases in PostgreSQL.