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

Введение

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, за дополнительной информацией всегда можно обратиться к документации на официальном сайте.

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_partkeydef ( table oid ) → text

Reconstructs the definition of a partitioned table’s partition key, in the form it would have in the PARTITION BY clause of CREATE TABLE. (This is a decompiled reconstruction, not the original text of the command.)

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.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 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.74. (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.75. 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.76 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.

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.

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.

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.

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.

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.

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.

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.

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.

PostgreSQL releases new versions on a regular basis. The major releases of Postgres are usually scheduled yearly and focus on fixing bugs and improving key features. In contrast, minor releases are scheduled nearly every three months. The minor releases focus on resolving the existing security issues.

If you intend to implement new software, you might want to check if it is compatible with your Postgres version, whether the latest security patch is available, etc. In such cases, knowing which Postgres version is active on your system might be useful.

This blog post will teach you how to check the current version of Postgres running on your system via different interfaces. So, let’s get started!

Contact us today for all your Postgres and Open Source consulting and support needs.

How to Check/Get Postgres Version Using Command Prompt?

Follow the below-given stepwise guidelines to check the currently installed Postgres version on your system via the command prompt.

Step1: Access Bin Directory

Firstly, open the command prompt and run the following command to navigate to the Postgres bin folder:

cd C:\Program Files\PostgreSQL\14\bin

img

Hit the “Enter” button to access the desired directory/path:

img

The above snippet indicates the successful entry into the “bin” directory.

Step2: Check Postgres Version

Now execute the “psql -v” command to check the Postgres version:

psql -V

img

Alternatively, you can execute the “psql –version” command to find the Postgres version:

psql –version

img

The output shows that the “Postgres 14.4” version is running on your computer.

How to Check/Get Postgres Version Using SQL Shell?

Launch the SQL Shell, fill in the login details, and run the below command to check which version of Postgres is running on your machine:

SELECT VERSION();

img

Alternatively, you can utilize the following command to check the server version:

SHOW SERVER_VERSION;

img

The output proves that the specified command returns the Postgres version.

How to Check/Get Postgres Version Using pgAdmin?

To get the Postgres version via pgAdmin, users can follow the below-mentioned steps:

Step 1: Expand “Servers” Tree

Firstly, open the pgAdmin, specify the superuser password, and left-click on the “Servers” tree to expand it:

img

Step 2: Select Properties

Now, left-click on the “PostgreSQL” located under the “Servers” tree, and then click on the “Properties” tab:

img

Under the properties tab, you can check the currently installed Postgres Version on your system.

Conclusion

PostgreSQL releases new versions on a regular basis. To check which Postgres version is active on your system, users can run “psql –version” command from the command prompt, the “SELECT VERSION()” command from SQL Shell, or expand the “Servers” tree, left-click on “PostgreSQL” and then click on the properties tab to check the Postgres Version via pgAdmin. This blog post explained various approaches for checking the PostgreSQL version via practical demonstration.

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.

There are a couple of ways we can check the PostgreSQL version. If you can connect to the server via psql, you can issue the following command that shows the server version:

SELECT version();

This function returns the PostgreSQL version, as well as the build system. It is also the preferred method to get the Postgres version on Windows.

You’ll get an answer that looks something like the following:

PostgreSQL 13.1 (Ubuntu 13.1-1.pgdg20.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit
(1 row)

The pg_lsclusters command is available in Ubuntu and Debian Linux distros. This command on Ubuntu shows all installed PostgreSQL clusters and their information.

pg_lsclusters

The pg_lsclusters output includes Postgres Version (Major release number), Port, Data directory, etc.

The following Linux command will also help you identify the PostgreSQL version by looking at the postmaster process.

pgrep -a post

It shows the command that started the PostgreSQL process. In my case, it is /usr/lib/postgresql/13/bin/postgres which I can use with the --version option to check PostgreSQL version.

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

check postgresql version

The PostgreSQL version number consists of two digits: major and minor release.

End of life (EOL): PostgreSQL developers provide support and upgrades for 5 years after a new stable version is released.

  • Как посмотреть видеоадаптер на windows 11
  • Как посмотреть версию internet explorer в windows 10
  • Как посмотреть видеокарту на компьютере windows 10 про
  • Как посмотреть версию directx на windows 11
  • Как посмотреть весь буфер обмена windows 10