Как узнать какая версия postgresql установлена windows

Как посмотреть версию PostgreSQL с помощью оболочки SQL Shell и командной строки. Проверка версии утилиты PSQL и исправление ошибки “Command ‘postgres’ not found”

Введение

PostgreSQL — объектно-реляционная система управления базами данных с открытым исходным кодом. Есть несколько способов узнать версию PostgreSQL, установленную на сервере. Технические специалисты должны располагать такими сведениями, например, чтобы своевременно производить обновление программного обеспечения, понимать, насколько текущая версия совместима для интеграции с той или иной службой, и для выполнения иных административных задач. Будем считать, что PostgreSQL уже установлена на сервере и работает. Если на этапе установки и настройки возникли какие-либо сложности, у нас в блоге есть статья, в которой рассмотрены базовые функции по работе с СУБД. В нашем случае, в качестве операционной системы выбрана Ubuntu Linux 22.04 и версия PostgreSQL 14.5, установленная из репозитория.

PostgreSQL как сервис

Узнать подробности

Разработчики придерживаются следующей схемы нумерации версий продукта: MAJOR.MINOR, где major — основная версия, которая снабжается новым функционалом, исправляет ошибки обновляет систему безопасности. Такой релиз выпускается примерно раз в год и поддерживается ближайшие 5 лет. Minor — дополнительная версия, выпускается не реже одного раза в три месяца и содержит в основном обновления системы безопасности.

Проверить версии PostgreSQL из командной строки

Для отображения версии PostgreSQL, нужно любым удобным способом подключиться к серверу и в терминале выполнить команду:

    pg_config --version

Результат выполнения:

    postgres (PostgreSQL) 14.5 (Ubuntu 14.5-0ubuntu0.22.04.1)

Из вывода команды видно, что используется версия PostgreSQL 14.5.

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

    postgres --version

Или используя короткую версию параметра -V:

    postgres -V

Обратите внимание, что в первом случае применяется длинная версия параметра —version, а во втором короткая -V, результат выполнения во всех трех случаях абсолютно одинаковый.

На этом этапе некоторые операционные системы могут сообщить об ошибке: Command ‘postgres’ not found, это не проблема, и связано с тем, что разработчики данного программного продукта по каким-либо причинам не размещают двоичный исполняемый файл postgres ни в одну из папок, прописанных в переменной окружения $PATH. В таком случае, найдем его самостоятельно:

    sudo find / -type f -iwholename "*/bin/postgres"

Результат выполнения команды в нашем случае:

    /usr/lib/postgresql/14/bin/postgres

Файл найден. Повторяем вышеописанные действия, используя абсолютный путь:

    /usr/lib/postgresql/14/bin/postgres --version

Или:

    /usr/lib/postgresql/14/bin/postgres -V

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

Узнать версию сервера PostgreSQL, используя оболочку

Также есть возможность определить версию СУБД непосредственно из оболочки самого сервера. На практике такой подход применим при написании SQL-запросов. Переходим в интерактивный терминал PostgreSQL от имени пользователя postgres:

    sudo -u postgres psql

Система попросит ввести свой пароль для использования функционала sudo. После ввода пароля должно появиться приглашение интерпретатора SQL-запросов в виде:

    postgres=#

Для отображения версии установленного сервера вводим запрос:

    SELECT version();

В ответ получим:

    ---------------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 14.5 (Ubuntu 14.5-0ubuntu0.22.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 11.2.0-19ubuntu1) 11.2.0, 64-bit
(1 row)

Из вывода команды видно, что установлена версия 14.5, а также другие технические данные о сервере.

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

    SHOW server_version;

Тогда ответ от сервера будет выглядеть следующим образом:

    server_version
-------------------------------------
 14.5 (Ubuntu 14.5-0ubuntu0.22.04.1)
(1 row)

Запущенный сервер сообщает номер версии — 14.5. Для выхода из SQL shell нужно ввести команду q и нажать Enter.

Посмотреть версию утилиты PSQL

PSQL — утилита, служащая интерфейсом между пользователем и сервером, она принимает SQL-запросы, затем передает их PostgreSQL серверу и отображает результат выполнения. Данный инструмент предоставляет очень мощный функционал для автоматизации и написания скриптов под широкий спектр задач. Для получения информации о версии установленной утилиты, нужно выполнить команду:

    psql -V

Или используя длинную версию параметра –version:

    psql --version

Вывод в обоих случаях будет одинаковый:

    psql (PostgreSQL) 14.5 (Ubuntu 14.5-0ubuntu0.22.04.1)

Терминальная утилита PSQL имеет версию 14.5.

Заключение

В этой инструкции мы:

  • разобрались в схеме управления версиями разработчиками продукта;
  • научились смотреть версию PostgreSQL в командной строке и с помощью клиентской оболочки PSQL;

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

Introduction

New versions of PostgreSQL are released at regular intervals. Major releases are scheduled yearly and focus on improving key features and fixing known bugs. Minor releases are available approximately every three months and aim to resolve ongoing security concerns.

You might want to check if you have the latest security patch, or if the new software you want to implement is compatible with your PostgreSQL version.

This tutorial shows you how to check your PostgreSQL version using a few short commands.

Title with PostgreSQL logo and versioning symbol.

Note: Have you considered installing SQL Workbench for Postgres? It’s a great tool for managing different database systems.

Prerequisites

  • Access to a terminal window/command line
  • PostgreSQL database server

Check PostgreSQL Version from Command Line

Access your terminal and enter the following command to check your PostgreSQL version:

postgres --version

The version number is displayed in your terminal window. Another way to check your PostgreSQL version is to use the -V option:

postgres -V

These two commands work with installations initiated from official repositories. They might not be applicable for installations originating from third-party sources. Instead, you might receive the “Command ‘postgres’ not found” message.

How to Solve the “Command ‘postgres’ not found” Error

To solve the “Command ‘postgres’ not found” issue, locate the PostgreSQL binary folder. Enter the following command to locate the correct postgres path:

locate bin/postgres

The path to your binary folder is now displayed in your terminal.

Path to postgres binary folder with the locate command.

Type the full path and add the -V option to display the current PostgreSQL server version:

/usr/lib/postgresql/10/bin/postgres -V

In this example, the Postgres version number is 10.12.

The postgres version number is presented in the terminal.

The PostgreSQL Development Group uses a standard MAJOR.MINOR semantic versioning system. In our example, the first section (10) signifies the MAJOR release number. The second part (12), represents the MINOR release number for that major version.

Note: Always update PostgreSQL to the latest available minor version that corresponds to the major version you have installed.

Check Postgres Version from SQL Shell

The version number can also be retrieved directly from the PostgreSQL prompt. Access the PostgreSQL shell prompt by typing the following command:

sudo -u postgres psql

Type the following SQL statement within the prompt to check the current version:

SELECT version();

The resulting output provides the full version and system information for the PostgreSQL server.

The location of the PostgreSQL version found from the Postgres shell.

You can also instruct PostgreSQL to show the value associated with the server_version parameter:

SHOW server_version;

The result displays the current value for server_version.

PostgreSQL version with the SHOW server_version statement.

How to Check psql Client Version

Psql functions as a front-end terminal for PostgreSQL. It’s used to issue queries and display the provided results.

You can use the following command to determine the version of the psql client utility:

psql --version

You’ll notice that the commands used to check the psql client version match the commands used to determine PostgreSQL server version. The -V option works in this instance as well:

psql -V

The psql version is presented in the terminal.

Pslq version displayed using the psql -V command.

The “Command not found” error can appear in this instance as well. If that is the case, enter the following command to locate the correct path to the psql utility:

locate bin/psql

The output provides the full path to the psql utility.

Full path to psql utility binary folder,

Use the resulting path and -V option to check the current psql version:

/usr/lib/postgresql/10/bin/psql -V

The resulting output shows you the current psql client version on your system.

Psql version using the full binary path.

Conclusion

The provided commands and SQL statements are the most effective way to determine the PostgreSQL version number. Use them to check the current version of your PostgreSQL database server or psql client utility.

Make sure that your systems are always up to date with the latest available version.

Function

Description

format_type ( type oid, typemod integer ) → text

Returns the SQL name for a data type that is identified by its type OID and possibly a type modifier. Pass NULL for the type modifier if no specific modifier is known.

pg_char_to_encoding ( encoding name ) → integer

Converts the supplied encoding name into an integer representing the internal identifier used in some system catalog tables. Returns -1 if an unknown encoding name is provided.

pg_encoding_to_char ( encoding integer ) → name

Converts the integer used as the internal identifier of an encoding in some system catalog tables into a human-readable string. Returns an empty string if an invalid encoding number is provided.

pg_get_catalog_foreign_keys () → setof record ( fktable regclass, fkcols text[], pktable regclass, pkcols text[], is_array boolean, is_opt boolean )

Returns a set of records describing the foreign key relationships that exist within the PostgreSQL system catalogs. The fktable column contains the name of the referencing catalog, and the fkcols column contains the name(s) of the referencing column(s). Similarly, the pktable column contains the name of the referenced catalog, and the pkcols column contains the name(s) of the referenced column(s). If is_array is true, the last referencing column is an array, each of whose elements should match some entry in the referenced catalog. If is_opt is true, the referencing column(s) are allowed to contain zeroes instead of a valid reference.

pg_get_constraintdef ( constraint oid [, pretty boolean ] ) → text

Reconstructs the creating command for a constraint. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_expr ( expr pg_node_tree, relation oid [, pretty boolean ] ) → text

Decompiles the internal form of an expression stored in the system catalogs, such as the default value for a column. If the expression might contain Vars, specify the OID of the relation they refer to as the second parameter; if no Vars are expected, passing zero is sufficient.

pg_get_functiondef ( func oid ) → text

Reconstructs the creating command for a function or procedure. (This is a decompiled reconstruction, not the original text of the command.) The result is a complete CREATE OR REPLACE FUNCTION or CREATE OR REPLACE PROCEDURE statement.

pg_get_function_arguments ( func oid ) → text

Reconstructs the argument list of a function or procedure, in the form it would need to appear in within CREATE FUNCTION (including default values).

pg_get_function_identity_arguments ( func oid ) → text

Reconstructs the argument list necessary to identify a function or procedure, in the form it would need to appear in within commands such as ALTER FUNCTION. This form omits default values.

pg_get_function_result ( func oid ) → text

Reconstructs the RETURNS clause of a function, in the form it would need to appear in within CREATE FUNCTION. Returns NULL for a procedure.

pg_get_indexdef ( index oid [, column integer, pretty boolean ] ) → text

Reconstructs the creating command for an index. (This is a decompiled reconstruction, not the original text of the command.) If column is supplied and is not zero, only the definition of that column is reconstructed.

pg_get_keywords () → setof record ( word text, catcode "char", barelabel boolean, catdesc text, baredesc text )

Returns a set of records describing the SQL keywords recognized by the server. The word column contains the keyword. The catcode column contains a category code: U for an unreserved keyword, C for a keyword that can be a column name, T for a keyword that can be a type or function name, or R for a fully reserved keyword. The barelabel column contains true if the keyword can be used as a bare column label in SELECT lists, or false if it can only be used after AS. The catdesc column contains a possibly-localized string describing the keyword’s category. The baredesc column contains a possibly-localized string describing the keyword’s column label status.

pg_get_ruledef ( rule oid [, pretty boolean ] ) → text

Reconstructs the creating command for a rule. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_serial_sequence ( table text, column text ) → text

Returns the name of the sequence associated with a column, or NULL if no sequence is associated with the column. If the column is an identity column, the associated sequence is the sequence internally created for that column. For columns created using one of the serial types (serial, smallserial, bigserial), it is the sequence created for that serial column definition. In the latter case, the association can be modified or removed with ALTER SEQUENCE OWNED BY. (This function probably should have been called pg_get_owned_sequence; its current name reflects the fact that it has historically been used with serial-type columns.) The first parameter is a table name with optional schema, and the second parameter is a column name. Because the first parameter potentially contains both schema and table names, it is parsed per usual SQL rules, meaning it is lower-cased by default. The second parameter, being just a column name, is treated literally and so has its case preserved. The result is suitably formatted for passing to the sequence functions (see Section 9.17).

A typical use is in reading the current value of the sequence for an identity or serial column, for example:

SELECT currval(pg_get_serial_sequence('sometable', 'id'));

pg_get_statisticsobjdef ( statobj oid ) → text

Reconstructs the creating command for an extended statistics object. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_triggerdef ( trigger oid [, pretty boolean ] ) → text

Reconstructs the creating command for a trigger. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_userbyid ( role oid ) → name

Returns a role’s name given its OID.

pg_get_viewdef ( view oid [, pretty boolean ] ) → text

Reconstructs the underlying SELECT command for a view or materialized view. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_viewdef ( view oid, wrap_column integer ) → text

Reconstructs the underlying SELECT command for a view or materialized view. (This is a decompiled reconstruction, not the original text of the command.) In this form of the function, pretty-printing is always enabled, and long lines are wrapped to try to keep them shorter than the specified number of columns.

pg_get_viewdef ( view text [, pretty boolean ] ) → text

Reconstructs the underlying SELECT command for a view or materialized view, working from a textual name for the view rather than its OID. (This is deprecated; use the OID variant instead.)

pg_index_column_has_property ( index regclass, column integer, property text ) → boolean

Tests whether an index column has the named property. Common index column properties are listed in Table 9.72. (Note that extension access methods can define additional property names for their indexes.) NULL is returned if the property name is not known or does not apply to the particular object, or if the OID or column number does not identify a valid object.

pg_index_has_property ( index regclass, property text ) → boolean

Tests whether an index has the named property. Common index properties are listed in Table 9.73. (Note that extension access methods can define additional property names for their indexes.) NULL is returned if the property name is not known or does not apply to the particular object, or if the OID does not identify a valid object.

pg_indexam_has_property ( am oid, property text ) → boolean

Tests whether an index access method has the named property. Access method properties are listed in Table 9.74. NULL is returned if the property name is not known or does not apply to the particular object, or if the OID does not identify a valid object.

pg_options_to_table ( options_array text[] ) → setof record ( option_name text, option_value text )

Returns the set of storage options represented by a value from pg_class.reloptions or pg_attribute.attoptions.

pg_settings_get_flags ( guc text ) → text[]

Returns an array of the flags associated with the given GUC, or NULL if it does not exist. The result is an empty array if the GUC exists but there are no flags to show. Only the most useful flags listed in Table 9.75 are exposed.

pg_tablespace_databases ( tablespace oid ) → setof oid

Returns the set of OIDs of databases that have objects stored in the specified tablespace. If this function returns any rows, the tablespace is not empty and cannot be dropped. To identify the specific objects populating the tablespace, you will need to connect to the database(s) identified by pg_tablespace_databases and query their pg_class catalogs.

pg_tablespace_location ( tablespace oid ) → text

Returns the file system path that this tablespace is located in.

pg_typeof ( "any" ) → regtype

Returns the OID of the data type of the value that is passed to it. This can be helpful for troubleshooting or dynamically constructing SQL queries. The function is declared as returning regtype, which is an OID alias type (see Section 8.19); this means that it is the same as an OID for comparison purposes but displays as a type name.

For example:

SELECT pg_typeof(33);
 pg_typeof
-----------
 integer

SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
 typlen
--------
      4

COLLATION FOR ( "any" ) → text

Returns the name of the collation of the value that is passed to it. The value is quoted and schema-qualified if necessary. If no collation was derived for the argument expression, then NULL is returned. If the argument is not of a collatable data type, then an error is raised.

For example:

SELECT collation for (description) FROM pg_description LIMIT 1;
 pg_collation_for
------------------
 "default"

SELECT collation for ('foo' COLLATE "de_DE");
 pg_collation_for
------------------
 "de_DE"

to_regclass ( text ) → regclass

Translates a textual relation name to its OID. A similar result is obtained by casting the string to type regclass (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found. Also unlike the cast, this does not accept a numeric OID as input.

to_regcollation ( text ) → regcollation

Translates a textual collation name to its OID. A similar result is obtained by casting the string to type regcollation (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found. Also unlike the cast, this does not accept a numeric OID as input.

to_regnamespace ( text ) → regnamespace

Translates a textual schema name to its OID. A similar result is obtained by casting the string to type regnamespace (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found. Also unlike the cast, this does not accept a numeric OID as input.

to_regoper ( text ) → regoper

Translates a textual operator name to its OID. A similar result is obtained by casting the string to type regoper (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found or is ambiguous. Also unlike the cast, this does not accept a numeric OID as input.

to_regoperator ( text ) → regoperator

Translates a textual operator name (with parameter types) to its OID. A similar result is obtained by casting the string to type regoperator (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found. Also unlike the cast, this does not accept a numeric OID as input.

to_regproc ( text ) → regproc

Translates a textual function or procedure name to its OID. A similar result is obtained by casting the string to type regproc (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found or is ambiguous. Also unlike the cast, this does not accept a numeric OID as input.

to_regprocedure ( text ) → regprocedure

Translates a textual function or procedure name (with argument types) to its OID. A similar result is obtained by casting the string to type regprocedure (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found. Also unlike the cast, this does not accept a numeric OID as input.

to_regrole ( text ) → regrole

Translates a textual role name to its OID. A similar result is obtained by casting the string to type regrole (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found. Also unlike the cast, this does not accept a numeric OID as input.

to_regtype ( text ) → regtype

Translates a textual type name to its OID. A similar result is obtained by casting the string to type regtype (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found. Also unlike the cast, this does not accept a numeric OID as input.

In this article I present several ways to check your PostgreSQL version.

Option 1: SELECT version()

If you’re already connected to PostgreSQL, run the following query to return the PostgreSQL server’s version information:

SELECT version();

Here’s the result when using PostgreSQL 12.1:

                                                   version                                                   
-------------------------------------------------------------------------------------------------------------
 PostgreSQL 12.1 on x86_64-apple-darwin16.7.0, compiled by Apple LLVM version 8.1.0 (clang-802.0.42), 64-bit
(1 row)

This option is handy for when you’re connected to a PostgreSQL database using a GUI such as PgAdmin, DBeaver, Azure Data Studio, etc.

But you can run the same query when you’re connected to a PostgreSQL database using the psql command line interface (CLI).

Option 2: SHOW server_version

If you only want the version number, run SHOW server_version:

SHOW server_version;

Here’s the result when using PostgreSQL 12.1:

server_version 
----------------
12.1

You can also use the server_version_num command to return the version number as an integer:

SHOW server_version_num;

Here’s the result when using PostgreSQL 12.1

server_version_num 
--------------------
120001

Option 3: Using the CLI

Here are a couple of handy Command Line Interface (CLI) options.

The pg_config Utility

The pg_config utility retrieves information about the installed version of PostgreSQL.

Running it with the --version option returns the PostgreSQL server’s version number:

pg_config --version

Here’s the result when using version 12.1:

PostgreSQL 12.1

Another way to do it is to use postgres -V.

postgres -V

Result:

postgres (PostgreSQL) 12.1

The psql Client

psql is a terminal-based front-end to PostgreSQL.

Running psql --version returns the psql version number:

psql --version

Here’s the result when using version 12.1:

psql (PostgreSQL) 12.1

You can also use a shortened syntax psql -V to return the same result.

psql -V

Result:

psql (PostgreSQL) 12.1

Содержание

  1. Как проверить версию PostgreSQL
  2. Версия PostgreSQL
  3. Использование командной строки
  4. Использование оболочки SQL
  5. Вывод
  6. Как проверить версию postgresql 2022
  7. instalar e configurar postgres 9.6
  8. Версия PostgreSQL
  9. Использование командной строки
  10. Использование оболочки SQL
  11. Вывод
  12. Как проверить версию BIOS в Windows 10
  13. Как проверить версию PowerShell в Windows 10
  14. Как проверить (проверить) открытые порты в Linux
  15. PostgreSQL. 10 продвинутых команд для DBA с примерами
  16. 1. Как найти самую большую таблицу в базе данных PostgreSQL?
  17. 2. Как узнать размер всей базы данных PostgreSQL?
  18. 3. Как узнать размер таблицы в базе данных PostgreSQL?
  19. 4. Как узнать текущую версию сервера PostgreSQL?
  20. 5. Как выполнить SQL-файл в PostgreSQL?
  21. 6. Как отобразить список всех баз данных сервера PostgreSQL?
  22. 7. Как отобразить список всех таблиц в базе данных PostgreSQL?
  23. 8. Как показать структуру, индексы и прочие элементы выбранной таблицы в PostgreSQL?
  24. 9. Как отобразить время выполнения запроса в консольной утилите PostgreSQL?
  25. 10. Как отобразить все команды консольной утилиты PostgreSQL?
  26. Как проверить версию PostgreSQL
  27. Управление версиями PostgreSQL
  28. Использование командной строки
  29. Использование оболочки SQL
  30. Выводы
  31. Linux и Windows: помощь админам и пользователям
  32. Администрируем и настраиваем Windows, Linux.
  33. 15 команд для управления PostgreSQL
  34. 1. Как изменить root пароль в PostgreSQL?
  35. 2. Как установить PostgreSQL в автозапуск?
  36. 3. Проверяем состояние сервера
  37. 4. Как запустить, остановить, перезапустить PostgreSQL?
  38. 5. Как посмотреть какая версия PostgreSQL запущена?
  39. 5. Как создать пользователя в PostgreSQL?
  40. 7. Получаем список всех баз в Postgresql?
  41. 8. Как удалить базу в PostgreSQL?
  42. 9. Пользуемя встроенным хелпом к командам
  43. 10. Как получить список всех таблиц в базе данный в Postgresql?
  44. 11. Как узнать время выполнения запроса?
  45. 12. Как бэкапить и восстанавливать базы и таблицы в PostgreSQL?
  46. 14. Как отредактировать запрос к PostgreSQL в редакторе?
  47. 15. Где я могу найти файл истории postgreSQL?
  48. Комментариев: 10

Как проверить версию PostgreSQL

Главное меню » Базы данных » Как проверить версию PostgreSQL

Знание того, какая версия сервера PostgreSQL установлена ​​и работает в вашей системе, может быть важно в некоторых ситуациях. Например, если вы устанавливаете приложение, для которого требуется определенная версия PostgreSQL, вам необходимо выяснить версию вашего сервера PostgreSQL.

В этой статье мы объясним, как узнать, какая версия сервера PostgreSQL работает в вашей системе.

Версия PostgreSQL

PostgreSQL имеет версии по следующей схеме:

Например, в PostgreSQL 12.1 12 – это основная версия и 1 – дополнительная версия.

Основные выпуски PostgreSQL с новыми функциями обычно выпускаются раз в год. Каждый основной релиз поддерживается в течение 5 лет.

Использование командной строки

Команда выведет версию PostgreSQL:

В этом примере используется версия сервера PostgreSQL 10.6.

Если двоичный файл postgres отсутствует в системном PATH, вы получите сообщение об ошибке «postgres: command not found». Обычно это происходит, когда пакет PostgreSQL не установлен из стандартных репозиториев дистрибутива.

Вы можете найти путь к двоичному файлу с помощью команды locate или find:

Вывод должен выглядеть примерно так:

Как только вы найдете путь к двоичному файлу, вы можете использовать его для получения версии сервера PostgreSQL:

Версию клиентской утилиты psql в PostgreSQL можно найти с помощью следующей команды:

Вывод будет выглядеть примерно так:

psql – интерактивная утилита командной строки, которая позволяет вам взаимодействовать с сервером PostgreSQL.

Использование оболочки SQL

Другой способ определить версию сервера PostgreSQL – войти в SQL-запрос сервера и использовать инструкцию SQL для распечатки версии.

Вы можете получить доступ к оболочке PostgreSQL с помощью GUI-клиента, такого как pgAdmin или с помощью psql:

Следующий оператор отображает версию сервера PostgreSQL вместе с информацией о сборке:

Если вы хотите получить только номер версии сервера PostgreSQL, используйте следующий запрос:

Вывод

В этой статье мы показали несколько разных вариантов того, как найти версию сервера PostgreSQL, работающую в вашей системе.

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

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Как проверить версию postgresql 2022

instalar e configurar postgres 9.6

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

Знание того, какая версия сервера PostgreSQL установлена ​​и работает в вашей системе, может быть важно в некоторых ситуациях. Например, если вы устанавливаете приложение, для которого требуется определенная версия PostgreSQL, вам необходимо выяснить версию вашего сервера PostgreSQL.

, мы объясним, как узнать, какая версия сервера PostgreSQL работает в вашей системе.

Версия PostgreSQL

Версии PostgreSQL имеют версии по следующей схеме:

Основные выпуски PostgreSQL с новыми функциями обычно выпускаются раз в год. Каждый основной релиз поддерживается в течение 5 лет.

Использование командной строки

Команда выведет версию PostgreSQL:

postgres (PostgreSQL) 10.6

Если двоичный файл postgres отсутствует в системной переменной PATH, вы получите сообщение об ошибке «postgres: команда не найдена». Обычно это происходит, когда пакет PostgreSQL не установлен из стандартных репозиториев дистрибутива.

Вы можете найти путь к двоичному файлу с помощью команды locate или find :

sudo updatedb locate bin/postgres

Вывод должен выглядеть примерно так:

Как только вы найдете путь к двоичному файлу, вы можете использовать его для получения версии сервера PostgreSQL:

Версию клиентской утилиты PostgreSQL, psql можно найти с помощью следующей команды:

Вывод будет выглядеть примерно так:

postgres (PostgreSQL) 10.6

Использование оболочки SQL

Вы можете получить доступ к оболочке PostgreSQL с помощью GUI-клиента, такого как pgAdmin или с помощью psql :

Следующий оператор отображает версию сервера PostgreSQL вместе с информацией о сборке:

Вывод

Мы показали несколько различных вариантов того, как найти версию сервера PostgreSQL, работающую в вашей системе.

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

Как проверить версию BIOS в Windows 10

how to check bios version in windows 10

В этом сообщении показано, как проверить текущую версию BIOS в Windows 10 / 8.1 / 8/7 с помощью Windows Registry, WMIC / CMD, System Information Tool или DXDiag.

Как проверить версию PowerShell в Windows 10

how to check powershell version in windows 10 2

Используйте эту команду для проверки, получения и отображения версии PowerShell, установленной на вашем Windows 10/8 / 7 / computer.

Как проверить (проверить) открытые порты в Linux

how check

В этой статье описывается несколько подходов, чтобы узнать, какие порты открыты снаружи в вашей системе Linux.

Источник

PostgreSQL. 10 продвинутых команд для DBA с примерами

// 25 октября, 2013 | 57767 просмотров

1. Как найти самую большую таблицу в базе данных PostgreSQL?

Результатом будет самая большая таблица (в примере testtable1 ) в страницах. Размер одной страницы равен 8KB (т.е. размер таблицы в примере — 2,3GB)

2. Как узнать размер всей базы данных PostgreSQL?

Результатом будет размер базы данных в байтах:

Если вы хотите получить размер в более читаемом («человеческом») формате — «оберните» результат в функцию pg_size_pretty() :

Ну и сразу логичным будет показать все базы данных в читаемом («человеческом») виде, отсортированные от более больших к меньшим

3. Как узнать размер таблицы в базе данных PostgreSQL?

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

Если вам нужно узнать размер таблицы без индексов, тогда следует выполнить такой запрос:

4. Как узнать текущую версию сервера PostgreSQL?

Результат будет подобным этому:

5. Как выполнить SQL-файл в PostgreSQL?

Для данной цели существует специальная команда в консольной утилите:

Где /path/to/file.sql — это путь к вашему SQL-файлу. Обратите внимание, что он должен лежать в доступной для чтения пользователя postgres директории.

6. Как отобразить список всех баз данных сервера PostgreSQL?

Для данной цели существует специальная команда в консольной утилите:

7. Как отобразить список всех таблиц в базе данных PostgreSQL?

Для данной цели существует специальная команда в консольной утилите что покажет список таблиц в текущей БД.

8. Как показать структуру, индексы и прочие элементы выбранной таблицы в PostgreSQL?

Для данной цели существует специальная команда в консольной утилите:

Где testtable1 — имя таблицы

9. Как отобразить время выполнения запроса в консольной утилите PostgreSQL?

После чего все запросы станут отображаться в консольной утилите со временем выполнения.
Отключаются эти уведомления точно так же, как и включаются — вызовом:

10. Как отобразить все команды консольной утилиты PostgreSQL?

Это наверное самый важный пункт, т.к. любой DBA должен знать как вызвать эту справку 🙂

Источник

Как проверить версию PostgreSQL

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

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

В этой статье мы объясним, как узнать, какая версия сервера PostgreSQL работает в вашей системе.

Управление версиями PostgreSQL

Версии выпусков PostgreSQL контролируются по следующей схеме:

Например, в PostgreSQL 12.1 12 — это основная версия, а 1 — дополнительная версия.

MAJOR — Начиная с PostgreSQL 10, каждый новый основной выпуск увеличивает MAJOR часть версии на единицу, например, 10, 11 или 12. До PostgreSQL 10 основные версии представлялись десятичным числом, например 9.0 или 9.6.

MINOR — второстепенный номер выпуска — это последняя часть номера версии. Например, 11.4 и 11.6 являются второстепенными версиями, которые являются частью PostgreSQL версии 11, а 9.6.15 и 9.6.16 являются частью PostgreSQL версии 9.6.

Основные выпуски PostgreSQL с новыми функциями обычно выпускаются один раз в год. Каждый основной выпуск поддерживается в течение 5 лет.

Использование командной строки

Команда выведет версию PostgreSQL:

Вы можете найти путь к двоичному файлу с помощью команды locate или find :

Результат должен выглядеть примерно так:

Найдя путь к двоичному файлу, вы можете использовать его для получения версии сервера PostgreSQL:

Версию клиентской утилиты PostgreSQL, psql можно найти с помощью следующей команды:

Результат будет выглядеть примерно так:

psql — это интерактивная утилита командной строки, которая позволяет вам взаимодействовать с сервером PostgreSQL.

Использование оболочки SQL

Другой способ определить версию сервера PostgreSQL — войти в запрос SQL сервера и использовать оператор SQL для печати версии.

Вы можете получить доступ к оболочке PostgreSQL с помощью клиента с графическим интерфейсом, например pgAdmin, или с помощью psql :

Следующий оператор отображает версию сервера PostgreSQL вместе с информацией о сборке:

Если вы хотите получить только номер версии сервера PostgreSQL, используйте следующий запрос:

Выводы

В этой статье мы показали несколько различных вариантов того, как найти версию сервера PostgreSQL, работающую в вашей системе.

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

Источник

Linux и Windows: помощь админам и пользователям

Администрируем и настраиваем Windows, Linux.

15 команд для управления PostgreSQL

В этой статье я покажу 15 наиболее полезных команд для управления postgreSQL.

1. Как изменить root пароль в PostgreSQL?

Изменение пароля для обычного пользователя происходит таким же образом. Пользователь root может поменять пароль любому пользователю.

2. Как установить PostgreSQL в автозапуск?

3. Проверяем состояние сервера

4. Как запустить, остановить, перезапустить PostgreSQL?

5. Как посмотреть какая версия PostgreSQL запущена?

5. Как создать пользователя в PostgreSQL?

Для этого существуют два метода..

Метод 1: Создаем пользователя в через PSQL шелл, командой CREATE USER.

Метод 2: Создаем пользователя в через шелл команду createuser.

Для этого существует 2 метода.

Метод 1: Создаем базу черезе PSQL шелл, с помощью команды CREATE DATABASE.

Метод 2: Используем команду createdb.

7. Получаем список всех баз в Postgresql?

8. Как удалить базу в PostgreSQL?

9. Пользуемя встроенным хелпом к командам

Команда ? отобразит строку помощи для команда PSQL. h CREATE покажет хелп для всех команд который начинаются с CREATE.

10. Как получить список всех таблиц в базе данный в Postgresql?

Для пустой базы вы получите сообщение “No relations found.”

11. Как узнать время выполнения запроса?

# timing — после выполения данной команды каждый последующий запрос будет показывать время выполнения.

12. Как бэкапить и восстанавливать базы и таблицы в PostgreSQL?

Этот вопрос довольно велик и я опубликую его позднее отдельной статьей.

Для того чтобы получить список доступных функций, скажите df+

14. Как отредактировать запрос к PostgreSQL в редакторе?

e откроет редактор, в котором вы можете отредактировать запрос и сохранить его.

15. Где я могу найти файл истории postgreSQL?

/.bash_history, postgreSQL хранит все sql команды в файле

Разное

Лучшие выставочные стенды в Москве. Отличное качество выполнения, невысокие цены.

Курьерская служба, доставка по Москве и Московской области, срочная доставка, рассылки писем, счетов, журналов

twitter facebook vkontakte odnoklassniki mail ru yaru rutvit myspace technorati digg friendfeed pikabu blogger liveinternet livejournal memori google bookmarks bobrdobr mister wong yahoo bookmarks delicious

Комментариев: 10

Очень хорошая статья, люблю живые примеры

С удовольствием прочитаю статью про бэкапы в postgresql

Спасибо, подборка очень выручила когда пришлось аврально разбираться, как с postgesql работать.

И да, примерах с кодом у меня повылазили тэги , лучше бы их убрать, читать мешает.

Не получается :((( команда postgresql status говорит что он остановлен.

Странно. Я пользуюсь Ruby On Rails и у меня иногда удаляется база данных. Причём, непонятно почему.

Как посмотреть какая версия PostgreSQL запущена?

Полная ахинея. Нужно быть придурком чтобы таким образом определять версию постгреса,

Автор просто скопипастил текст «статьи» откуда-то даже не удосужившись удалить html-тэги.

Также хочется отметить, что способов запуска/остановки процессов в разных системах минимум 2, тут выделен самый неудачный в плане длинного пути и отсутствия стандартизации запуска процессов.

Есть команда показывающая место расположения базы данных:

Источник

Using CLI:

Server version:

$ postgres -V  # Or --version.  Use "locate bin/postgres" if not found.
postgres (PostgreSQL) 9.6.1
$ postgres -V | awk '{print $NF}'  # Last column is version.
9.6.1
$ postgres -V | egrep -o '[0-9]{1,}.[0-9]{1,}'  # Major.Minor version
9.6

If having more than one installation of PostgreSQL, or if getting the «postgres: command not found» error:

$ locate bin/postgres | xargs -i xargs -t '{}' -V  # xargs is intentionally twice.
/usr/pgsql-9.3/bin/postgres -V 
postgres (PostgreSQL) 9.3.5
/usr/pgsql-9.6/bin/postgres -V 
postgres (PostgreSQL) 9.6.1

If locate doesn’t help, try find:

$ sudo find / -wholename '*/bin/postgres' 2>&- | xargs -i xargs -t '{}' -V  # xargs is intentionally twice.
/usr/pgsql-9.6/bin/postgres -V 
postgres (PostgreSQL) 9.6.1

Although postmaster can also be used instead of postgres, using postgres is preferable because postmaster is a deprecated alias of postgres.

Client version:

As relevant, login as postgres.

$ psql -V  # Or --version
psql (PostgreSQL) 9.6.1

If having more than one installation of PostgreSQL:

$ locate bin/psql | xargs -i xargs -t '{}' -V  # xargs is intentionally twice.
/usr/bin/psql -V 
psql (PostgreSQL) 9.3.5
/usr/pgsql-9.2/bin/psql -V 
psql (PostgreSQL) 9.2.9
/usr/pgsql-9.3/bin/psql -V 
psql (PostgreSQL) 9.3.5

Using SQL:

Server version:

=> SELECT version();
                                                   version                                                    
--------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.2.9 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4), 64-bit

=> SHOW server_version;
 server_version 
----------------
 9.2.9

=> SHOW server_version_num;
 server_version_num 
--------------------
 90209

If more curious, try => SHOW all;.

Client version:

For what it’s worth, a shell command can be executed within psql to show the client version of the psql executable in the path. Note that the running psql can potentially be different from the one in the path.

=> ! psql -V
psql (PostgreSQL) 9.2.9

Понравилась статья? Поделить с друзьями:
  • Как узнать какая у меня лицензия windows 10
  • Как узнать какая версия net framework установлена на windows 10 x64
  • Как узнать какая у меня звуковая карта на windows 10
  • Как узнать какая версия mysql установлена windows
  • Как узнать какая у меня встроенная видеокарта на windows 10