Введение
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 |
---|
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. |
Converts the supplied encoding name into an integer representing the internal identifier used in some system catalog tables. Returns |
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. |
Returns a set of records describing the foreign key relationships that exist within the PostgreSQL system catalogs. The |
Reconstructs the creating command for a constraint. (This is a decompiled reconstruction, not the original text of the command.) |
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. |
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 |
Reconstructs the argument list of a function or procedure, in the form it would need to appear in within |
Reconstructs the argument list necessary to identify a function or procedure, in the form it would need to appear in within commands such as |
Reconstructs the |
Reconstructs the creating command for an index. (This is a decompiled reconstruction, not the original text of the command.) If |
Returns a set of records describing the SQL keywords recognized by the server. The |
Reconstructs the definition of a partitioned table’s partition key, in the form it would have in the |
Reconstructs the creating command for a rule. (This is a decompiled reconstruction, not the original text of the command.) |
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 ( 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')); |
Reconstructs the creating command for an extended statistics object. (This is a decompiled reconstruction, not the original text of the command.) |
Reconstructs the creating command for a trigger. (This is a decompiled reconstruction, not the original text of the command.) |
Returns a role’s name given its OID. |
Reconstructs the underlying |
Reconstructs the underlying |
Reconstructs the underlying |
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.) |
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.) |
Tests whether an index access method has the named property. Access method properties are listed in Table 9.75. |
Returns the set of storage options represented by a value from |
Returns an array of the flags associated with the given GUC, or |
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 |
Returns the file system path that this tablespace is located in. |
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 For example: SELECT pg_typeof(33); pg_typeof ----------- integer SELECT typlen FROM pg_type WHERE oid = pg_typeof(33); typlen -------- 4 |
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 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" |
Translates a textual relation name to its OID. A similar result is obtained by casting the string to type |
Translates a textual collation name to its OID. A similar result is obtained by casting the string to type |
Translates a textual schema name to its OID. A similar result is obtained by casting the string to type |
Translates a textual operator name to its OID. A similar result is obtained by casting the string to type |
Translates a textual operator name (with parameter types) to its OID. A similar result is obtained by casting the string to type |
Translates a textual function or procedure name to its OID. A similar result is obtained by casting the string to type |
Translates a textual function or procedure name (with argument types) to its OID. A similar result is obtained by casting the string to type |
Translates a textual role name to its OID. A similar result is obtained by casting the string to type |
Translates a textual type name to its OID. A similar result is obtained by casting the string to type |
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
Hit the “Enter” button to access the desired directory/path:
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
Alternatively, you can execute the “psql –version” command to find the Postgres version:
psql –version
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();
Alternatively, you can utilize the following command to check the server version:
SHOW SERVER_VERSION;
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:
Step 2: Select Properties
Now, left-click on the “PostgreSQL” located under the “Servers” tree, and then click on the “Properties” tab:
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.
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.
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 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.
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.
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.
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.
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.
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
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.