Посмотреть все базы данных postgresql linux

PostgreSQL Show Databases

In this tutorial, you will learn how to show databases in a PostgreSQL database server.

In MySQL, you can show all databases in the database server using SHOW DATABASES statement.

PostgreSQL does not directly support the SHOW DATABASES statement but offers you something similar. PostgreSQL provides you with two ways to show databases in the current database server.

Listing databases in PostgreSQL using psql command

If you are using the psql tool to connect to PostgreSQL database server, you can issue the \l command to shows all databases in the current server as follows:

\lCode language: Shell Session (shell)

First, launch the psql tool. It will prompt you for the following information: server, database, port, and username. If you press the Enter keyboard, it will use the default value specified in the square brackets ( [] ). However, you need to provide the password for the user that you use to login:

Server [localhost]: Database [postgres]: Port [5432]: Username [postgres]: Password for user postgres:Code language: Shell Session (shell)

Second, use the \l command in the PostgreSQL prompt like this:

postgres=# \lCode language: Shell Session (shell)

It will show the following output:

If you want to get more information, you can use the \l+ command:

postgres=# \l+Code language: Shell Session (shell)

Listing databases in PostgreSQL using SELECT statement

Besides using the \l or \l+ command, you can use the SELECT statement to query database names from the pg_database catalog that contains information on databases.

SELECT datname FROM pg_database;Code language: SQL (Structured Query Language) (sql)
 datname ----------- postgres template1 template0 dvdrental (4 rows)Code language: Shell Session (shell)

The query shows four databases in the current database server.

Summary

  • Use \l or \l+ in psql to show all databases in the current PostgreSQL server.
  • Use the SELECT statement to query data from the pg_database to get all databases.

Источник

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:

Читайте также:  Лучший linux для ssd

This tutorial will show you how to list all databases in PostgreSQL and inspect which tables a database contains.

Learn how to list all databases in PostgreSQL.

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.

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.

Connect to the database server using psql terminal.

Step 3: Run the following command:

Output showing a list of all databases in PostgreSQL

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:

SELECT datname FROM pg_database;

List all databases in psql using the SELECT statement.

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.

Open pgAdmin and 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.

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:

An example of connecting to a database in psql

Step 2: List all database tables by running:

The output of table names and their schema, type, and owner

The output includes table names and their schema, type, and owner.

Читайте также:  Files types in linux

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.

See all tables of a database in pgAdmin.

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.

Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.

Use this guide to check your PostgreSQL version with a few straightforward commands. You can retrieve the PostgresSQL version directly from your command line or use an effective SQL statement within the PostgreSQL shell.

Learn how to export a PostgreSQL table to a .csv file. This feature is especially helpful when transferring the table to a different system or importing it to another database application.

Save time and effort by managing different database systems with a single tool. Find out how to set up SQL Workbench to connect to a PostgreSQL database with four (4) easy steps.

PostgreSQL is the third most popular Docker image used for deploying containers. Run PostgreSQL on Docker by pulling the Postgres image from Docker’s official repository and set up the database service for your application.

Источник

Как вывести список баз данных и таблиц PostgreSQL с помощью psql

При администрировании серверов баз данных PostgreSQL одной из наиболее распространенных задач, которые вы, вероятно, будете выполнять, будет перечисление баз данных и их таблиц.

PostgreSQL поставляется с интерактивным инструментом psql , который позволяет вам подключаться к серверу и выполнять запросы к нему. При использовании psql вы также можете воспользоваться его мета-командами. Эти команды полезны для написания сценариев и администрирования из командной строки. Все мета-команды начинаются с обратной косой черты без кавычек и также известны как команды с обратной косой чертой.

В этом руководстве объясняется, как отображать базы данных и таблицы на сервере PostgreSQL с помощью psql .

Читайте также:  Включить java firefox linux

Листинг баз данных

Вы можете подключиться к серверу PostgreSQL с помощью команды psql как любой системный пользователь. В зависимости от конфигурации сервера пользователю может потребоваться ввести свой пароль для подключения к терминалу psql . Чтобы получить доступ к терминалу psql от имени пользователя, в который вы сейчас вошли, просто введите psql .

При установке пакета PostgreSQL создается административный пользователь с именем «postgres». По умолчанию этот пользователь может подключаться к локальному серверу PostgreSQL без пароля.

Чтобы получить доступ к терминалу psql от имени пользователя postgres, запустите:

В терминале psql выполните мета-команду l или list вывести список всех баз данных:

Вывод будет включать количество баз данных, имя каждой базы данных, ее владельца, кодировку и права доступа:

 List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+---------+---------+----------------------- odoo | odoo | UTF8 | C | C.UTF-8 | postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) 

На сервере PostgreSQL по умолчанию созданы три базы данных: template0, template1 и postgres. Первые два — это шаблоны, которые используются при создании новых баз данных.

Если вы хотите получить информацию о размерах баз данных, табличных пространствах по умолчанию и описаниях, используйте l+ или list+ . Размер базы данных отображается только в том случае, если текущий пользователь может к ней подключиться.

Чтобы получить список всех баз данных без доступа к оболочке psql, используйте переключатель -c как показано ниже:

Другой способ составить список баз данных — использовать следующий оператор SQL:

SELECT datname FROM pg_database; 

В отличие от мета-команды l приведенный выше запрос покажет только имена баз данных:

 datname ----------- postgres odoo template1 template0 (4 rows) 

Листинговые таблицы

Чтобы сначала вывести список всех таблиц конкретной базы данных, вам необходимо подключиться к ней с помощью c или connect . Пользователь, в который вы вошли в терминал psql, должен иметь возможность подключаться к базе данных.

Например, чтобы подключиться к базе данных с именем «odoo», введите:

После переключения базы данных используйте мета-команду dt вывести список всех таблиц базы данных:

Вывод будет включать количество таблиц, имя каждой таблицы, ее схему, тип и владельца:

 List of relations Schema | Name | Type | Owner --------+-----------------------------------------------------+-------+------- public | base_import_import | table | odoo public | base_import_mapping | table | odoo public | base_import_tests_models_char | table | odoo . public | web_editor_converter_test_sub | table | odoo public | web_tour_tour | table | odoo public | wizard_ir_model_menu_create | table | odoo (107 rows) 

Если база данных пуста, вывод будет выглядеть так:

Чтобы получить информацию о размерах таблиц и описаниях, используйте dt+ .

Выводы

Вы узнали, как составить список баз данных и таблиц PostgreSQL с помощью команды psql .

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

Оцените статью
Adblock
detector