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

Knowing the specific version of PostgreSQL is vital for maintaining compatibility and utilizing new features. In this article, we will explain several methods to check our PostgreSQL version using the command line, the SQL shell, and the psql client. Also, it addresses common errors such as the «Command ‘postgres’ not found«.

Checking PostgreSQL Version from the Command Line

When working with Postgres, the exact version we are using is essential for compatibility, performance tuning and taking advantage of the latest features and security improvements.

Checking the PostgreSQL version from the command line is one of the quickest methods available. Let’s go over two commands that can help us determine the server and client versions.

1. Using the PSQL Command (Client Version)

The PSQL command is the PostgreSQL interactive terminal that allows us to communicate with the database. The —version option displays the installed version of the psql client.

To check the version of the PostgreSQL client installed on your system, use the following command

psql --version

Output:

Using-the-psql-Command

Using the psql Command

Explanation: This output indicates that the psql client version installed on my machine is 16.2, meaning i am using the client that interacts with a PostgreSQL 16.x server.

2. Using the postgres Command (Server Version)

The Postgres -V command directly checks the version of the PostgreSQL server. It’s useful for confirming the server version in case you are maintaining or configuring multiple versions of PostgreSQL.

To check the PostgreSQL server version, use the postgres command

postgres -V

Output:

Using-the-postgres-Command

Using the postgres Command

Explanation:

The output shows that my PostgreSQL server version is 16.2. It’s important to note that the client and server versions should match or compatible to avoid communication errors.

Solve «Command ‘postgres’ not found» When Using postgres -V

Sometimes, when we try to run Postgres -V, we might encounter the «Command ‘postgres’ not found» error. This issue occurs either because PostgreSQL is not installed correctly or because the PATH environment variable is not configured. Here’s how we can fix this:

Step 1. Verify Installation: Run the following command to verify if PostgreSQL is installed on your system.

This command lists the installed packages and should return a result if PostgreSQL is installed. If nothing is returned, we need to install PostgreSQL.

sudo apt list --installed | grep postgresql

Step 2. Add PostgreSQL to PATH: If PostgreSQL is installed but not found, add the PostgreSQL binary folder to your PATH:

export PATH=$PATH:/usr/lib/postgresql/14/bin

Step 3. Reinstall PostgreSQL: If the issue persists, reinstall PostgreSQL using the following command

sudo apt install postgresql

These steps will help resolve the error and ensure that the Postgres -V command works properly to check your server version.

Check Postgres Version from SQL Shell

The SQL Shell (PSQL) is another way to determine the PostgreSQL version. This method provides detailed information, including platform and compiler details. This query returns detailed information about the PostgreSQL server, including the version number, platform, and compiler used to build PostgreSQL.

Step 1: Log in to the PostgreSQL shell

Step 2: Run the following SQL command, This query returns the PostgreSQL version along with additional details like the OS platform and compiler version used to build the database.

SELECT version();

Output:

Check-Postgres-Version-from-SQL-Shell

Check Postgres Version from SQL Shell

Explanation:

The output shows that PostgreSQL version 16.2 is installed on a 64-bit system. Additionally, it provides details about the C++ compiler version used to build the database.

How to Check psql Client Version?

The psql client is a command-line interface that connects us to the PostgreSQL server. Checking the client version helps ensure that it’s compatible with the server.

This command is similar to the one mentioned earlier and returns the version of the PostgreSQL psql client installed on your system. Run the following command to check the PSQLclient version,

psql --version

Solve «Command ‘postgres’ not found» when Checking psql Client Version

If we are checking the psql client version and encounter the «Command ‘postgres’ not found» error, the solution is similar to what we discussed earlier. Following these steps will help us to resolve the «command not found» issue when checking the PSQL client version.

Step 1: Check if psql is Installed: Run the following command to verify if the PSQL client is installed

sudo apt list --installed | grep psql

Step 2: If it’s not listed: you can install it using

sudo apt install postgresql-client

Step 3: Add psql to PATH: If the client is installed but not accessible, add it to your system PATH using the following command

export PATH=$PATH:/usr/lib/postgresql/14/bin

Conclusion

In summary, quickly checking PostgreSQL versions via command line commands like psql --version and postgres -V is essential for effective database management. These methods enable users to confirm compatibility between client and server versions.

Существует несколько способов узнать версию системы управления базами данных PostgreSQL в операционной системе Windows.

Узнать версию PostgreSQL при помощи графической оболочки

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

select version();

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

Узнать версию PostgreSQL при помощи оболочки

Узнать версию PostgreSQL при помощи SQL Shell (psql)

Находим утилиту SQL Shell (psql) и запускаем её.

Запуск утилиты SQL Shell (psql)

Теперь необходимо подключиться к серверу PostgreSQL:

  • Server [localhost] — оставляем пустым, нажимаем Enter;
  • Database [postgres] — указываем имя базы данных my_db, нажимаем Enter;
  • Port [5432] — оставляем пустым, нажимаем Enter;
  • Username [postgres] — оставляем пустым, нажимаем Enter;
  • Пароль пользователя postgres — вводим пароль, который был указан при установке.

После подключения к серверу, выполняем следующий запрос:

select version();

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

Узнать версию PostgreSQL при помощи SQL Shell (psql)

Метки: PostgreSQL.

New versions of PostgreSQL are released by the PostgreSQL Global Development Group on a regular basis. The major releases of Postgres are usually scheduled yearly and focus on improving key features as well as performance and security. In contrast, minor releases are scheduled nearly every three months. The minor releases focus on resolving evolving security issues and fixing bugs.

Try the new PgManage (Open Source) and get rid of PgAdmin!

If you intend to implement new software, you should 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.

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

Quick Outline

This blog post will teach you how to check the current version of Postgres running on your system using the following content.

  • How to Check/Get Postgres Version on Windows?
  • How to Check/Get Postgres Version on macOS?
  • How to Check/Get Postgres Version on Linux?
  • Final Thoughts

So, let’s get started!

How to Check/Get Postgres Version on Windows?

To check the Postgres version on the Windows operating system different methods like CMD (Command Prompt), psql (SQL Shell), and pgAdmin are used. All these methods will be discussed in this section using appropriate screenshots:

Method 1: How to Check PostgreSQL Version Using the Command Prompt

Follow the below-given stepwise guidelines to check the currently installed PostgreSQL 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.

Method 2: How to Check the PostgreSQL Version Using SQL Shell

SQL Shell is a default Postgres terminal that helps us execute different SQL commands and meta-commands. Different commands like “SELECT VERSION()”, and “SHOW_VERSION” can be executed from SQL Shell to Check the Postgres version.

Launch the SQL Shell, fill in the login details, and run the below command to check which version of PostgreSQL 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 PostgreSQL version.

Method 3: How to Check PostgreSQL Version Using pgAdmin

pgAdmin is a feature-rich GUI-based tool that is an open-source and freely available management tool for Postgres. Using pgAdmin, you can find the current Postgres version either manually or by executing SQL queries.

To check the PostgreSQL version via pgAdmin, users can follow the below-mentioned steps:

Step 1: Expand “Servers” Tree

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

img

Step 2: Select Properties

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 PostgreSQL version on your system.

Note: You can also execute the “SELECT VERSION();” and “SHOW SERVER_VERSION;” commands in the pgAdmin’s query tool.

How to Check/Get Postgres Version on macOS?

Mac users can find the Postgres version either by using a terminal or pgAdmin. To find the Postgres version via pgAdmin, perform the same steps as we did for Windows. While to check the PostgreSQL version via the Mac Terminal, execute the command:

postgres -V

img

How to Check/Get Postgres Version on Linux?

To find the Postgres version on Linux, the “SQL Shell”, “pg_config” utility, the “dpkg” command, and the “apt-cache” command are used. All these methods are discussed with practical illustration in our dedicated guide on “Check Postgres Version on Linux”.

Final Thoughts

PostgreSQL is among the top databases that keep its users up-to-date by releasing new versions regularly. Postgres users can upgrade the currently used version to the latest one to avail the latest features. But before that, it’s recommended to check which Postgres version you are currently using.

To do that on the Windows system, users can run the “psql —version” command from the Command Prompt, the “SELECT VERSION()” command from SQL Shell, or use pgAdmin’s properties tab. Linux users can use the “SQL Shell”, “pg_config” utility, the “dpkg” command, or the “apt-cache” command to check the currently installed Postgres version. This blog post explained various approaches for checking the PostgreSQL version on Windows, MacOS, and Linux via practical demonstration.

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

Какую версию PostgreSQL выбрать?

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

Поэтому важно учитывать, какие версии поддерживаются на момент выбора. На 2025 год актуальны версии 17-13. 13 версия PostgreSQL в осенью 2025 году

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

Как обозначаются версии в PostgreSQL?

До PostgreSQL 10 использовалась трехзначная схема версий (например, 9.6.3), где:

  • первая цифра — основная версия,
  • вторая — второстепенные обновления,
  • третья — патчи.

С PostgreSQL 10 схема изменилась: теперь используются две цифры, например 16.1, где:

  • первая цифра — основная версия,
  • вторая — обновление.

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

Сообщество PostgreSQL не рекомендует выход в продуктовые среды с минорной версией СУБД PostgreSQL младше 3 (например 17.2), так как на этом этапе еще идет процесс тестирования под различными нагрузками и сценариями. И поэтому можно столкнуться с проблемами ранней версии СУБД.

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

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

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

В Linux и macOS можно выполнить команду в терминале, чтобы узнать версию установленной СУБД. В Windows аналогичная команда работает в командной строке или PowerShell. Она выводит текущую версию PostgreSQL.

Узнать версию PostgreSQL с помощью SQL-запроса

Если есть доступ к базе данных, можно использовать SQL-запрос SELECT version();. Он вернет строку, содержащую информацию о версии PostgreSQL, архитектуре системы и параметрах компиляции.

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

Если PostgreSQL установлен, но сервер не запущен, можно воспользоваться утилитой pg_config —version. Это поможет определить версию установленной, но не работающей в данный момент СУБД.

Когда может потребоваться помощь экспертов?

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

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

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

Если вам требуется помощь в проверке версии, выборе конфигурации или обновлении PostgreSQL, эксперты ДБ-Сервис готовы взять эти задачи на себя.

Наши специалисты обеспечат корректный переход на новую версию и исключат возможные ошибки.

Заключение

Знание версии PostgreSQL помогает поддерживать базу данных в актуальном состоянии, избегать уязвимостей и использовать все возможности СУБД. Проверить версию можно через командную строку, SQL-запрос или утилиты. Если требуется обновление, важно учитывать поддержку и совместимость, а в сложных случаях — привлекать экспертов.

Опыт работы: 13 лет опыта работы с базами данных, более 6 лет опыта работы архитектором БД и DBA. Опыт построения отказоустойчивых кластеров на базе СУБД PostgreSQL и GreenPlum 6x. Постоянный докладчик на Российских и международных IT конференциях.

Иван Чувашов

Ведущий инженер в Data Driven Lab / Сертифицированный администратор PostgreSQL (PostgresPro, 10 уровень «Эксперт»)

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Телефоны работающие на windows mobile
  • Как поменять dos на windows
  • Не удалось получить список устройств с центра обновления windows повторите попытку позже
  • Лаунчер в стиле windows mobile
  • Драйвер ati radeon hd 4350 драйвер windows 7 64