Как вывести список баз данных и таблиц PostgreSQL с помощью psql
При администрировании серверов баз данных PostgreSQL одной из наиболее распространенных задач, которые вы, вероятно, будете выполнять, будет перечисление баз данных и их таблиц.
PostgreSQL поставляется с интерактивным инструментом psql , который позволяет вам подключаться к серверу и выполнять запросы к нему. При использовании psql вы также можете воспользоваться его мета-командами. Эти команды полезны для написания сценариев и администрирования из командной строки. Все мета-команды начинаются с обратной косой черты без кавычек и также известны как команды с обратной косой чертой.
В этом руководстве объясняется, как отображать базы данных и таблицы на сервере PostgreSQL с помощью psql .
Листинг баз данных
Вы можете подключиться к серверу PostgreSQL с помощью команды psql как любой системный пользователь. В зависимости от конфигурации сервера пользователю может потребоваться ввести свой пароль для подключения к терминалу psql . Чтобы получить доступ к терминалу psql от имени пользователя, в который вы сейчас вошли, просто введите psql .
При установке пакета PostgreSQL создается административный пользователь с именем «postgres». По умолчанию этот пользователь может подключаться к локальному серверу PostgreSQL без пароля.
Чтобы получить доступ к терминалу psql от имени пользователя postgres, запустите:
В терминале psql выполните мета-команду l или list вывести список всех баз данных:
Вывод будет включать количество баз данных, имя каждой базы данных, ее владельца, кодировку и права доступа:
На сервере PostgreSQL по умолчанию созданы три базы данных: template0, template1 и postgres. Первые два — это шаблоны, которые используются при создании новых баз данных.
Если вы хотите получить информацию о размерах баз данных, табличных пространствах по умолчанию и описаниях, используйте l+ или list+ . Размер базы данных отображается только в том случае, если текущий пользователь может к ней подключиться.
Чтобы получить список всех баз данных без доступа к оболочке psql, используйте переключатель -c как показано ниже:
Другой способ составить список баз данных — использовать следующий оператор SQL:
В отличие от мета-команды l приведенный выше запрос покажет только имена баз данных:
Листинговые таблицы
Чтобы сначала вывести список всех таблиц конкретной базы данных, вам необходимо подключиться к ней с помощью c или connect . Пользователь, в который вы вошли в терминал psql, должен иметь возможность подключаться к базе данных.
Например, чтобы подключиться к базе данных с именем «odoo», введите:
После переключения базы данных используйте мета-команду dt вывести список всех таблиц базы данных:
Вывод будет включать количество таблиц, имя каждой таблицы, ее схему, тип и владельца:
Если база данных пуста, вывод будет выглядеть так:
Чтобы получить информацию о размерах таблиц и описаниях, используйте dt+ .
Выводы
Вы узнали, как составить список баз данных и таблиц PostgreSQL с помощью команды psql .
How to List All Databases in PostgreSQL
One of the important tasks when managing PostgreSQL servers is listing the existing databases and their tables. There are three ways to list all databases:
- Using meta-commands
- Running a query against a server
- Via the GUI tool pgAdmin.
This tutorial will show you how to list all databases in PostgreSQL and inspect which tables a database contains.
- PostgreSQL installed and set up
- Administrator privileges
List Databases via psql Terminal
The psql terminal is a front end to PostgreSQL, allowing users to interact with the server by running queries, issuing them to PostgreSQL, and displaying the results.
psql allows users to use meta-commands, useful commands starting with a backslash \ . Use these commands to perform routine tasks, such as to connect to a database, see all databases, etc.
Note: Read our tutorial and learn to create databases in PostgreSQL.
To list all the databases in the server via the psql terminal, follow these steps:
Step 1: Open the SQL Shell (psql) app.
Step 2: Press ENTER four times to connect to the DB server. Enter your password if asked. If you didn’t set up a password, press ENTER again to connect.
Step 3: Run the following command:
The output shows a list of all databases currently on the server, including the database name, the owner, encoding, collation, ctype, and access privileges.
Note: If you want to see additional information about size, tablespace, and database descriptions in the output, use \l+ .
List Databases via SQL Query
Another method to list databases in PostgreSQL is to query database names from the pg_database catalog via the SELECT statement. Follow these steps:
Step 1: Log in to the server using the SQL Shell (psql) app.
Step 2: Run the following query:
psql runs the query against the server and displays a list of existing databases in the output.
Note: Learn the difference between PostgreSQL and MySQL in our comparison article.
List Databases via pgAdmin
The third method to see databases on the server is to use pgAdmin. pgAdmin is the leading open-source GUI tool for managing PostgreSQL databases.
Follow these steps to see all databases on the server using pgAdmin:
Step 1: Open the pgAdmin app and enter your password to connect to the database server.
Step 2: Expand the Servers tree and then the Databases tree. The tree expands to show a list of all databases on the server. Click the Properties tab to see more information about each database.
List Tables
After listing all existing databases on the server, you can view the tables a database contains. You can achieve this by using psql or using pgAdmin.
See tables in psql
Step 1: While you’re logged in, connect to the database you want to inspect. The syntax is:
Step 2: List all database tables by running:
The output includes table names and their schema, type, and owner.
If there are no tables in a database, the output states that no relations were found.
Note: To see more information about tables, including their sizes and descriptions, run \dt+ .
See tables in pgAdmin:
Step 1: After logging in to pgAdmin, expand the Servers tree, Databases tree, and click the database you want to inspect.
Step 2: In the expanded database tree, click Schemas, followed by Tables. The Properties tab shows a list of all tables, and they show up in the Tables tree as well.
The guide provided the instructions for listing all databases and their tables on your PostgreSQL server. Choose pgAdmin for a GUI approach or use psql if you prefer to administer your database via a terminal.
Fore more tutorials about PostgreSQL, make sure to read our article and find out how to drop a PostgreSQL database.
PostgreSQL List Databases
PostgreSQL list databases are defined as list all the databases from the database server; we can list the database by using the pg_database catalog table. We can also see the list of the databases by using the \l command; also, we can see the more description of the database by using the \l+ command in PostgreSQL. To list the database in PostgreSQL is very important and useful to see all created databases on the PostgreSQL server. To see a list of databases in PostgreSQL, we need to connect to the database through psql; we can also see the database using shell prompt.
Syntax
- \l
- \l+
- \list
- \list+
- Select name_of_column1, name_of_column2, name_of_column3, …, name_of_columnN from pg_database (name_of_table);
Below is the parameter description syntax of list databases in PostgreSQL.
Hadoop, Data Science, Statistics & others
- \l –This command is used to list all databases with information of database name, owner of the database, encoding, collate, ctype, and access privileges of the database.
- \l+ – This command is used to list all databases with information of database name, owner of the database, encoding, collate, ctype and access privileges of the database, size of the database, database tablespace name, and description for the database.
- \list –This command is the same work as the \l command in PostgreSQL. This command is used to list all databases with information of database name, owner of the database, encoding, collate, ctype, and access privileges of the database.
- \list+ – This command is the same work as \l+ command in PostgreSQL. This command is used to list all databases with information of database name, owner of the database, encoding, collate, ctype and access privileges of the database, size of the database, database tablespace name, description for the database, encoding, collate, ctype and access privileges for the databases.
- Select –This operation is used to select a column from the pg_database table to list the databases. We can select specific or all column from the table to see the list of databases in PostgreSQL.
- Name of the column –This is defined as the name of the column for the table of pg_database. We can select a single or all column which was we want to display in the output.
- Pg_database –This is a catalog table of PostgreSQL that contains the information of all the database created by the user and contains the information of system databases.
How to list databases in PostgreSQL?
- We can list the databases are as follows.
- To list the databases in PostgreSQL, we do not need to provide any privileges to the user; any user can list the databases in PostgreSQL.
- The below example shows that we do not need to provide any privilege to list database for user in PostgreSQL.
- In the above first example, we have checked the privileges of the user; the db_test user doesn’t have any privileges on the database server.
- In the second example, we use db_test user to list databases; using db_test user, it’s possible to list the databases in PostgreSQL because we do not need to be given any privileges to list the databases in PostgreSQL.
psql -U postgres
\du
psql -U db_test -d postgres
\l
- Basically, we have using the below command to list all the databases is as follows.
- \l
- \l+
- \list
- \list+
- Select * from pg_database;
- We can use the metadata command and pg_database catalog table to list the databases in PostgreSQL.
- Using the above command, we have a list system as well as user-created databases.
- We can list the database by using shell prompt as well as using database shell prompt in PostgreSQL.
- We can also use limited options to list the database by using the pg_database catalog table. Pg_database catalog table is very important to fetch the information related to all the databases.
Examples
Below is an example of a list of the databases.
1. List the databases by using \l command
The below example shows that list the databases by using \l command.
2. List the databases by using the \l+ command
The below example shows that list the databases by using the \l+ command.
3. List the databases by using \list command
The below example shows that list the databases by using \list command.
4. List the databases by using \list+ command
The below example shows that list the databases by using \list+ command.
5. List the databases by using shell prompt
The below example shows that list the databases by using shell prompt. In the below example, we have listed all the databases by using the shell prompt using the command as \l+.
psql -U postgres -d postgres -c «\l+»
6. List the databases by using the pg_database catalog table
The below example shows that list the databases by using the pg_database catalog table.
select * from pg_database;
7. List the specific number of databases by using limit
The below example shows that list the specific number of databases by using limits.
select * from pg_database limit 3;
select * from pg_database limit 5;
8. Display only a list of the database name
The below example shows display only a list of database names present in the database server.
select datname from pg_database;
Recommended Articles
This is a guide to PostgreSQL List Databases. Here we discuss How to list databases in PostgreSQL along with the examples. You may also have a look at the following articles to learn more –
Вывести все базы/таблицы в PostgreSQL
Эта статья «Вывести все базы/таблицы в PostgreSQL» поможет показать вам список всех баз данных и таблиц в PostgreSQL. Для начала, войти в PostgreSQL с помощью команды PSQL и выполнить следующую команду из командной строки PostgreSQL.
Вывести все базы в PostgreSQL
Вы можете использовать любую из перечисленных команд что ниже, чтобы вывести список всех баз данных в PostgreSQL:
Вывести все таблицы в PostgreSQL
Чтобы просмотреть список таблиц в любой базе данных, сначала необходимо подключиться к этой БД, а затем выполнить команду для просмотра таблиц. Первая команда подключит вас к БД (например: your_DB) в которой вы хотите увидеть таблицы и вторая команда покажет их:
На этом все, я завершил свою тему «Вывести все базы/таблицы в PostgreSQL».
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.