Postgresql как установить под windows 10

PostgreSQL — это бесплатная объектно-реляционная СУБД с мощным функционалом, который позволяет конкурировать с платными базами данных, такими как Microsoft SQL, Oracle. PostgreSQL поддерживает пользовательские данные, функции, операции, домены и индексы. В данной статье мы рассмотрим установку и краткий обзор по управлению базой данных PostgreSQL. Мы установим СУБД PostgreSQL в Windows 10, создадим новую базу, добавим в неё таблицы и настроим доступа для пользователей. Также мы рассмотрим основы управления PostgreSQL с помощью SQL shell и визуальной системы управления PgAdmin. Надеюсь эта статья станет хорошей отправной точкой для обучения работы с PostgreSQL и использованию ее в разработке и тестовых проектах.

Содержание:

  • Установка PostgreSQL 11 в Windows 10
  • Доступ к PostgreSQL по сети, правила файерволла
  • Утилиты управления PostgreSQL через командную строку
  • PgAdmin: Визуальный редактор для PostgresSQL
  • Query Tool: использование SQL запросов в PostgreSQL

Установка PostgreSQL 11 в Windows 10

Для установки PostgreSQL перейдите на сайт https://www.postgresql.org и скачайте последнюю версию дистрибутива для Windows, на сегодняшний день это версия PostgreSQL 11 (в 11 версии PostgreSQL поддерживаются только 64-х битные редакции Windows). После загрузки запустите инсталлятор.

где скачать PostgreSQL 11 для windows 10 x64

В процессе установки установите галочки на пунктах:

  • PostgreSQL Server – сам сервер СУБД
  • PgAdmin 4 – визуальный редактор SQL
  • Stack Builder – дополнительные инструменты для разработки (возможно вам они понадобятся в будущем)
  • Command Line Tools – инструменты командной строки

установка PostgreSQL 11 и дополнительных компонентов

Установите пароль для пользователя postgres (он создается по умолчанию и имеет права суперпользователя).

PostgreSQL - задать пароль пользователю postgres

По умолчание СУБД слушает на порту 5432, который нужно будет добавить в исключения в правилах фаерволла.

5432 - порт PostgreSQL по-умолчанию

Нажимаете Далее, Далее, на этом установка PostgreSQL завершена.

Доступ к PostgreSQL по сети, правила файерволла

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

Запустите командную строку от имени администратора. Введите команду:

netsh advfirewall firewall add rule name="Postgre Port" dir=in action=allow protocol=TCP localport=5432

  • Где rule name – имя правила
  • Localport – разрешенный порт

Либо вы можете создать правило, разрешающее TCP/IP доступ к экземпляру PostgreSQL на порту 5432 с помощью PowerShell:

New-NetFirewallRule -Name 'POSTGRESQL-In-TCP' -DisplayName 'PostgreSQL (TCP-In)' -Direction Inbound -Enabled True -Protocol TCP -LocalPort 5432

После применения команды в брандмауэре Windows появится новое разрешающее правило для порта Postgres.

правила бранжмауэра для доступа к PostgreSQL по сети

Совет. Для изменения порта в установленной PostgreSQL отредактируйте файл postgresql.conf по пути C:\Program Files\PostgreSQL\11\data.

Измените значение в пункте
port = 5432
. Перезапустите службу сервера postgresql-x64-11 после изменений. Можно перезапустить службу с помощью PowerShell:

Restart-Service -Name postgresql-x64-11

служба postgresql-x64-11

Более подробно о настройке параметров в конфигурационном файле postgresql.conf с помощью тюнеров смотрите в статье.

Утилиты управления PostgreSQL через командную строку

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

  • Запустите командную строку.

    Совет. Перед запуском СУБД, смените кодировку для нормального отображения в русской Windows 10. В командной строке выполните:
    chcp 1251

  • Перейдите в каталог bin выполнив команду:
    CD C:\Program Files\PostgreSQL\11\bin

утилиты управления postgresql - C:\Program Files\PostgreSQL\11\bin

Основные команды PostgreSQL:

PostgreSQL (shell): psql командная строка

PgAdmin: Визуальный редактор для PostgresSQL

Редактор PgAdmin служит для упрощения управления базой данных PostgresSQL в понятном визуальном режиме.

По умолчанию все созданные базы хранятся в каталоге base по пути C:\Program Files\PostgreSQL\11\data\base.

Для каждой БД существует подкаталог внутри PGDATA/base, названный по OID базы данных в pg_database. Этот подкаталог по умолчанию является местом хранения файлов базы данных; в частности, там хранятся её системные каталоги. Каждая таблица и индекс хранятся в отдельном файле.

Для резервного копирования и восстановления лучше использовать инструмент Backup в панели инструментов Tools. Для автоматизации бэкапа PostgreSQL из командной строки используйте утилиту pg_dump.exe.

Query Tool: использование SQL запросов в PostgreSQL

Для написания SQL запросов в удобном графическом редакторе используется встроенный в pgAdmin инструмент Query Tool. Например, вы хотите создать новую таблицу в базе данных через инструмент Query Tool.

  • Выберите базу данных, в панели Tools откройте Query Tool
  • Создадим таблицу сотрудников:

CREATE TABLE employee
(
Id SERIAL PRIMARY KEY,
FirstName CHARACTER VARYING(30),
LastName CHARACTER VARYING(30),
Email CHARACTER VARYING(30),
Age INTEGER
);

Query Tool: использование SQL запросов в PostgreSQL

Id — номер сотрудника, которому присвоен ключ SERIAL. Данная строка будет хранить числовое значение 1, 2, 3 и т.д., которое для каждой новой строки будет автоматически увеличиваться на единицу. В следующих строках записаны имя, фамилия сотрудника и его электронный адрес, которые имеют тип CHARACTER VARYING(30), то есть представляют строку длиной не более 30 символов. В строке — Age записан возраст, имеет тип INTEGER, т.к. хранит числа.

После того, как написали код SQL запроса в Query Tool, нажмите клавишу F5 и в базе будет создана новая таблица employee.

Для заполнения полей в свойствах таблицы выберите таблицу employee в разделе Schemas -> Tables. Откройте меню Object инструмент View/Edit Data.

Здесь вы можете заполнить данные в таблице.

редактор таблица в pgadmin

После заполнения данных выполним инструментом Query простой запрос на выборку:
select Age from employee;

выполнить select в PostgreSQL с помощью PgAdmin

In this tutorial, you’ll learn how to install PostgreSQL 14.7 on Windows 10.

The process is straightforward and consists of the following steps:

  1. Install PostgreSQL
  2. Configure Environment Variables
  3. Verify the Installation
  4. Download the Northwind PostgreSQL SQL file
  5. Create a New PostgreSQL Database
  6. Import the Northwind SQL file
  7. Verify the Northwind database installation
  8. Connect to the Database Using Jupyter Notebook

Prerequisites

  • A computer running Windows 10
  • Internet connection
  1. Download the official PostgreSQL 14.7 at https://get.enterprisedb.com/postgresql/postgresql-14.7-2-windows-x64.exe
  2. Save the installer executable to your computer and run the installer.

Note: We recommend version 14.7 because it is commonly used. There are newer versions available, but their features vary substantially!

Step 1: Install PostgreSQL

We’re about to initiate a vital part of this project — installing and configuring PostgreSQL.

Throughout this process, you’ll define critical settings like the installation directory, components, data directory, and the initial ‘postgres’ user password. This password grants administrative access to your PostgreSQL system. Additionally, you’ll choose the default port for connections and the database cluster locale.

Each choice affects your system’s operation, file storage, available tools, and security. We’re here to guide you through each decision to ensure optimal system functioning.

  1. In the PostgreSQL Setup Wizard, click Next to begin the installation process.

  2. Accept the default installation directory or choose a different directory by clicking Browse. Click Next to continue.

  3. Choose the components you want to install (e.g., PostgreSQL Server, pgAdmin 4 (optional), Stack Builder (optional), Command Line Tools),no characters will appear on the screen as you type your password and click Next.

  4. Select the data directory for storing your databases and click Next.

  5. Set a password for the PostgreSQL “postgres” user and click Next.

    • There will be some points where you’re asked to enter a password in the command prompt. It’s important to note that for security reasons, as you type your password, no characters will appear on the screen. This standard security feature is designed to prevent anyone from looking over your shoulder and seeing your password. So, when you’re prompted for your password, don’t be alarmed if you don’t see any response on the screen as you type. Enter your password and press ‘Enter’. Most systems will allow you to re-enter the password if you make a mistake.

    • Remember, it’s crucial to remember the password you set during the installation, as you’ll need it to connect to your PostgreSQL databases in the future.

  6. Choose the default port number (5432) or specify a different port, then click Next.

  7. Select the locale to be used by the new database cluster and click Next.

  8. Review the installation settings and click Next to start the installation process. The installation may take a few minutes.

  9. Once the installation is complete, click Finish to close the Setup Wizard.

Step 2: Configure Environment Variables

Next, we’re going to configure environment variables on your Windows system. Why are we doing this? Well, environment variables are a powerful feature of operating systems that allow us to specify values — like directory locations — that can be used by multiple applications. In our case, we need to ensure that our system can locate the PostgreSQL executable files stored in the «bin» folder of the PostgreSQL directory.

By adding the PostgreSQL «bin» folder path to the system’s PATH environment variable, we’re telling our operating system where to find these executables. This means you’ll be able to run PostgreSQL commands directly from the command line, no matter what directory you’re in, because the system will know where to find the necessary files. This makes working with PostgreSQL more convenient and opens up the possibility of running scripts that interact with PostgreSQL.

Now, let’s get started with the steps to configure your environment variables on Windows!

  1. On the Windows taskbar, right-click the Windows icon and select System.

  2. Click on Advanced system settings in the left pane.

  3. In the System Properties dialog, click on the Environment Variables button.

  4. Under the System Variables section, scroll down and find the Path variable. Click on it to select it, then click the Edit button.

  5. In the Edit environment variable dialog, click the New button and add the path to the PostgreSQL bin folder, typically C:\\Program Files\\PostgreSQL\\14\\bin.

  6. Click OK to close the «Edit environment variable» dialog, then click OK again to close the «Environment Variables» dialog, and finally click OK to close the «System Properties» dialog.

Step 3: Verify the Installation

After going through the installation and configuration process, it’s essential to verify that PostgreSQL is correctly installed and accessible. This gives us the assurance that the software is properly set up and ready to use, which can save us from troubleshooting issues later when we start interacting with databases.

If something went wrong during installation, this verification process will help you spot the problem early before creating or managing databases.

Now, let’s go through the steps to verify your PostgreSQL installation.

  1. Open the Command Prompt by pressing Win + R, typing cmd, and pressing Enter.
  2. Type psql --version and press Enter. You should see the PostgreSQL version number you installed if the installation was successful.
  3. To connect to the PostgreSQL server, type psql -U postgres and press Enter.
  4. When prompted, enter the password you set for the postgres user during installation. You should now see the postgres=# prompt, indicating you are connected to the PostgreSQL server.

Step 4: Download the Northwind PostgreSQL SQL File

Now, we’re going to introduce you to the Northwind database and help you download it. The Northwind database is a sample database originally provided by Microsoft for its Access Database Management System. It’s based on a fictitious company named «Northwind Traders,» and it contains data on their customers, orders, products, suppliers, and other aspects of the business. In our case, we’ll be working with a version of Northwind that has been adapted for PostgreSQL.

The following steps will guide you on how to download this PostgreSQL-compatible version of the Northwind database from GitHub to your local machine. Let’s get started:

First, you need to download a version of the Northwind database that’s compatible with PostgreSQL. You can find an adapted version on GitHub. To download the SQL file, follow these steps:

  1. Open your Terminal application.

  2. Create a new directory for the Northwind database and navigate to it:

    mkdir northwind && cd northwind

  3. Download the Northwind PostgreSQL SQL file using curl:

    curl -O <https://raw.githubusercontent.com/pthom/northwind_psql/master/northwind.sql>

    This will download the northwind.sql file to the northwind directory you created.

Step 5: Create a New PostgreSQL Database

Now that we’ve downloaded the Northwind SQL file, it’s time to prepare our PostgreSQL server to host this data. The next steps will guide you in creating a new database on your PostgreSQL server, a crucial prerequisite before importing the Northwind SQL file.

Creating a dedicated database for the Northwind data is good practice as it isolates these data from other databases in your PostgreSQL server, facilitating better organization and management of your data. These steps involve connecting to the PostgreSQL server as the postgres user, creating the northwind database, and then exiting the PostgreSQL command-line interface.

Let’s proceed with creating your new database:

  1. Connect to the PostgreSQL server as the postgres user:

    psql -U postgres

  2. Create a new database called northwind:

    postgres-# CREATE DATABASE northwind;

  3. Exit the psql command-line interface:

    postgres-# \\q

Step 6: Import the Northwind SQL File

We’re now ready to import the Northwind SQL file into our newly created northwind database. This step is crucial as it populates our database with the data from the Northwind SQL file, which we will use for our PostgreSQL learning journey.

These instructions guide you through the process of ensuring you’re in the correct directory in your Terminal and executing the command to import the SQL file. This command will connect to the PostgreSQL server, target the northwind database, and run the SQL commands contained in the northwind.sql file.

Let’s move ahead and breathe life into our northwind database with the data it needs!

With the northwind database created, you can import the Northwind SQL file using psql. Follow these steps:

  1. In your Terminal, ensure you’re in the northwind directory where you downloaded the northwind.sql file.
  2. Run the following command to import the Northwind SQL file into the northwind database:

    psql -U postgres -d northwind -f northwind.sql

    This command connects to the PostgreSQL server as the postgres user, selects the northwind database, and executes the SQL commands in the northwind.sql file.

Step 7: Verify the Northwind Database Installation

You’ve successfully created your northwind database and imported the Northwind SQL file. Next, we must ensure everything was installed correctly, and our database is ready for use.

These upcoming steps will guide you on connecting to your northwind database, listing its tables, running a sample query, and finally, exiting the command-line interface. Checking the tables and running a sample query will give you a sneak peek into the data you now have and verify that the data was imported correctly. This means we can ensure everything is in order before diving into more complex operations and analyses.

To verify that the Northwind database has been installed correctly, follow these steps:

  1. Connect to the northwind database using psql:

    psql -U postgres -d northwind

  2. List the tables in the Northwind database:

    postgres-# \\dt

    You should see a list of Northwind tables: categories, customers, employees, orders, and more.

  3. Run a sample query to ensure the data has been imported correctly. For example, you can query the customers table:

    postgres-# SELECT * FROM customers LIMIT 5;

    This should return the first five rows from the customers table.

  4. Exit the psql command-line interface:

    postgres-# \\q

Congratulations! You’ve successfully installed the Northwind database in PostgreSQL using an SQL file and psql.

Step 8: Connect to the Database Using Jupyter Notebook

As we wrap up our installation, we will now introduce Jupyter Notebook as one of the tools available for executing SQL queries and analyzing the Northwind database. Jupyter Notebook offers a convenient and interactive platform that simplifies the visualization and sharing of query results, but it’s important to note that it is an optional step. You can also access Postgres through other means. However, we highly recommend using Jupyter Notebook for its numerous benefits and enhanced user experience.

To set up the necessary tools and establish a connection to the Northwind database, here is an overview of what each step will do:

  1. !pip install ipython-sql: This command installs the ipython-sql package. This package enables you to write SQL queries directly in your Jupyter Notebook, making it easier to execute and visualize the results of your queries within the notebook environment.

  2. %load_ext sql: This magic command loads the sql extension for IPython. By loading this extension, you can use the SQL magic commands, such as %sql and %%sql, to run SQL queries directly in the Jupyter Notebook cells.

  3. %sql postgresql://postgres@localhost:5432/northwind: This command establishes a connection to the Northwind database using the PostgreSQL database system. The connection string has the following format:

    postgresql://username@hostname:port/database_name

    In this case, username is postgres, hostname is localhost, port is 5432, and database_name is northwind. The %sql magic command allows you to run a single-line SQL query in the Jupyter Notebook.

  4. Copy the following text into a code cell in the Jupyter Notebook:

    !pip install ipython-sql
    %load_ext sql
    %sql postgresql://postgres@localhost:5432/northwind

    On Windows you may need to try the following command because you need to provide the password you set for the “postgres” user during installation:

    %sql postgresql://postgres:{password}@localhost:5432/northwind

    Bear in mind that it’s considered best practice not to include sensitive information like passwords directly in files that could be shared or accidentally exposed. Instead, you can store your password securely using environment variables or a password management system (we’ll link to some resources at the end of this guide if you are interested in doing this).

  5. Run the cell by either:

    • Clicking the «Run» button on the menu bar.
    • Using the keyboard shortcut: Shift + Enter or Ctrl + Enter.
  6. Upon successful connection, you should see an output similar to the following:

    'Connected: postgres@northwind'

    This output confirms that you are now connected to the Northwind database, and you can proceed with the guided project in your Jupyter Notebook environment.

Once you execute these commands, you’ll be connected to the Northwind database, and you can start writing SQL queries in your Jupyter Notebook using the %sql or %%sql magic commands.

Next Steps

Based on what you’ve accomplished, here are some potential next steps to continue your learning journey:

  1. Deepen Your SQL Knowledge:
    • Try formulating more complex queries on the Northwind database to improve your SQL skills. These could include joins, subqueries, and aggregations.
    • Understand the design of the Northwind database: inspect the tables, their relationships, and how data is structured.
  2. Experiment with Database Management:
    • Learn how to backup and restore databases in PostgreSQL. Try creating a backup of your Northwind database.
    • Explore different ways to optimize your PostgreSQL database performance like indexing and query optimization.
  3. Integration with Python:
    • Learn how to use psycopg2, a popular PostgreSQL adapter for Python, to interact with your database programmatically.
    • Experiment with ORM (Object-Relational Mapping) libraries like SQLAlchemy to manage your database using Python.
  4. Security and Best Practices:
    • Learn about database security principles and apply them to your PostgreSQL setup.
    • Understand best practices for storing sensitive information, like using .env files for environment variables.
    • For more guidance on securely storing passwords, you might find the following resources helpful:
      • Using Environment Variables in Python
      • Python Secret Module

На этом занятии мы рассмотрим процесс установки системы управления базами данных PostgreSQL на операционную систему Windows 10.

Кроме этого мы также установим и настроим pgAdmin 4 – это стандартный и бесплатный графический инструмент управления PostgreSQL, который мы можем использовать для написания SQL запросов, разработки процедур, функций, а также для администрирования PostgreSQL.

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

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

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

Что такое PostgreSQL

PostgreSQL — это бесплатная объектно-реляционная система управления базами данных (СУБД). PostgreSQL реализована для многих операционных систем, включая: BSD, Linux, macOS, Solaris и Windows.

В PostgreSQL в качестве расширения стандарта SQL используется язык PL/pgSQL.

PL/pgSQL – это процедурное расширение языка SQL, разработанное и используемое в СУБД PostgreSQL.

Язык PL/pgSQL предназначен для создания функций, триггеров, он добавляет управляющие структуры к языку SQL, и он помогает нам выполнять сложные вычисления.

Системные требования для установки PostgreSQL на Windows

PostgreSQL можно установить не на все версии Windows, в частности официально поддерживаются только Windows Server 2012 R2, 2016 и 2019 и только 64 битные версии.

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

Кроме этого есть и другие требования:

  • Процессор как минимум с частотой 1 гигагерц;
  • 2 гигабайта оперативной памяти;
  • Как минимум 512 мегабайт свободного места на диске (рекомендуется больше для установки дополнительных компонентов);
  • Также рекомендовано, чтобы все обновления операционной системы Windows были установлены.

Установка PostgreSQL и pgAdmin 4 на Windows 10

Итак, давайте перейдем к процессу установки, и рассмотрим все шаги, которые необходимо выполнить, чтобы установить PostgreSQL и pgAdmin 4 на Windows 10.

Шаг 1 – Скачивание установщика для Windows

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

Страница загрузки PostgreSQL — https://www.postgresql.org/download/windows/

После перехода на страницу необходимо нажимать на ссылку «Download the installer», в результате Вас перенесёт на сайт компании EnterpriseDB, которая и подготавливает графические дистрибутивы PostgreSQL для многих платформ, в том числе и для Windows, поэтому можете сразу переходить на этот сайт, вот ссылка на страницу загрузки https://www.enterprisedb.com/downloads/postgres-postgresql-downloads

Здесь Вам необходимо выбрать версию PostgreSQL и платформу, в нашем случае выбираем PostgreSQL 12 и Windows x86-64.

Скриншот 1

В итоге должен загрузиться файл установщика размером около 200 мегабайт.

Шаг 2 – Запуск установщика PostgreSQL

Теперь, чтобы начать установку, необходимо запустить скаченный файл (установка PostgreSQL требует прав администратора).

После запуска откроется окно приветствия, нажимаем «Next».

Скриншот 2

Шаг 3 – Указываем каталог для установки PostgreSQL

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

Нажимаем «Next».

Скриншот 3

Шаг 4 – Выбираем компоненты для установки

Затем выбираем компоненты, которые нам необходимо установить, для этого оставляем галочки напротив нужных нам компонентов. Обязательно нам нужны PostgreSQL Server и pgAdmin 4. Утилиты командной строки и Stack Builder устанавливайте по собственному желанию, т.е. их можно и не устанавливать, на процесс обучения они не влияют.

Нажимаем «Next».

Скриншот 4

Шаг 5 – Указываем каталог для хранения файлов баз данных

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

Нажимаем «Next».

Скриншот 5

Шаг 6 – Задаем пароль для системного пользователя postgres

Далее нам нужно задать пароль для пользователя postgres – это администратор PostgreSQL Server с максимальными правами.

Вводим и подтверждаем пароль. Нажимаем «Next».

Скриншот 6

Шаг 7 – Указываем порт для экземпляра PostgreSQL

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

Нажимаем «Next».

Скриншот 7

Шаг 8 – Указываем кодировку данных в базе

Затем мы можем указать конкретную кодировку данных в базе, для этого необходимо выбрать из выпадающего списка нужную Locale.

Однако можно оставить и по умолчанию, жмем «Next».

Скриншот 8

Шаг 9 – Проверка параметров установки PostgreSQL

Все готово к установке, на данном шаге проверяем введенные нами ранее параметры и нажимаем «Next».

Скриншот 9

Шаг 10 – Запуск процесса установки

Далее появится еще одно дополнительное окно, в котором мы должны нажать «Next», чтобы запустить процесс установки PostgreSQL на компьютер.

Скриншот 10

Установка началась, она продлится буквально 2-3 минуты.

Скриншот 11

Шаг 11 – Завершение установки

Когда отобразится окно с сообщением «Completing the PostgreSQL Setup Wizard», установка PostgreSQL, pgAdmin и других компонентов будет завершена.

Если Вы устанавливали Stack Builder, то Вам еще предложат запустить его для загрузки и установки дополнительных компонентов, если Вам это не нужно, то снимайте галочку «Lanch Stack Builder at exit?».

Нажимаем «Finish».

Скриншот 12

Запуск и настройка pgAdmin 4

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

Чтобы запустить pgAdmin, зайдите в меню пуск, найдите пункт PostgreSQL 12, а в нем pgAdmin 4.

Подключение к серверу PostgreSQL

pgAdmin 4 имеет веб интерфейс, поэтому в результате у Вас должен запуститься браузер, а в нем открыться приложение pgAdmin.

При первом запуске pgAdmin появится окно «Set Master Password», в котором мы должны задать «мастер-пароль», это можно и не делать, однако если мы будем сохранять пароль пользователя (галочка «Сохранить пароль»), например, для того чтобы каждый раз при подключении не вводить его, то настоятельно рекомендуется придумать и указать здесь дополнительный пароль, это делается один раз.

Вводим и нажимаем «ОК».

Скриншот 13

Чтобы подключиться к только что установленному локальному серверу PostgreSQL в обозревателе серверов, щелкаем по пункту «PostgreSQL 12».

В итоге запустится окно «Connect to Server», в котором Вам нужно ввести пароль системного пользователя postgres, т.е. это тот пароль, который Вы придумали, когда устанавливали PostgreSQL. Вводим пароль, ставим галочку «Save Password», для того чтобы сохранить пароль и каждый раз не вводить его (благодаря функционалу «мастер-пароля», все сохраненные таким образом пароли будут дополнительно шифроваться).

Нажимаем «OK».

Скриншот 14

В результате Вы подключитесь к локальному серверу PostgreSQL и увидите все объекты, которые расположены на данном сервере.

Скриншот 15

Установка русского языка в pgAdmin 4

Как видите, по умолчанию интерфейс pgAdmin на английском языке, если Вас это не устраивает, Вы можете очень просто изменить язык на тот, который Вам нужен. pgAdmin 4 поддерживает много языков, в том числе и русский.

Для того чтобы изменить язык pgAdmin, необходимо зайти в меню «File -> Preferences».

Скриншот 16

Затем найти пункт «User Languages», и в соответствующем поле выбрать значение «Russian». Для сохранения настроек нажимаем «Save», после этого перезапускаем pgAdmin 4 или просто обновляем страницу в браузере.

Скриншот 17

В результате pgAdmin будет русифицирован.

Скриншот 18

Пример написания SQL запроса в Query Tool (Запросник)

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

Для написания SQL запросов в pgAdmin используется инструмент Query Tool или на русском «Запросник», его можно запустить с помощью иконки на панели или из меню «Инструменты».

После того как Вы откроете Query Tool, напишите следующую инструкцию

SELECT VERSION();

Этот запрос показывает версию PostgreSQL.

Скриншот 19

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

Можно ли установить PostgreSQL на Linux?

На какие версии Windows можно установить PostgreSQL?

На какие версии Windows можно установить pgAdmin 4?

Какие приложения, кроме pgAdmin 4, можно использовать для подключения к PostgreSQL и выполнения SQL запросов?

Дополнительные материалы для самостоятельного изучения

Dear readers of our blog, we’d like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.

SQLS*Plus — best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

17 August 2020

Installing and configuring PostgreSQL 12 on Windows 10

You  will study in detail the process of installing PostgreSQL 12 on Windows 10.

In addition, we will also install and configure pgAdmin 4, which is a standard and free graphical tool for PostgreSQL DBMS management that we can use for writing SQL queries, developing procedures, functions, as well as for PostgreSQL administration.

What is PostgreSQL?

PostgreSQL is a free object-relational database management system (DBMS). PostgreSQL is implemented for many operating systems such as: BSD, Linux, macOS, Solaris and Windows.

PostgreSQL uses the PL/pgSQL language.

PL/pgSQL is a procedural extension of the SQL language, developed and used in PostgreSQL DBMS.

PL/pgSQL language is designed to create functions, triggers, it adds control structures to SQL language, and it helps us to perform complex calculations.

PostgreSQL is one of the most popular database management systems (TOP 5 popular database management systems).

At the time of writing, the most up-to-date version of PostgreSQL 12 is the one we will be installing.

System requirements for PostgreSQL 12 installation on Windows

PostgreSQL 12 can not be installed on all versions of Windows, in particular, the following versions are officially supported and only 64-bit:

  • Windows Server 2012 R2;
  • Windows Server 2016;
  • Windows Server 2019.

As you can see, there’s no Windows 10 on the official list, but installation on this system goes smoothly, as does subsequent PostgreSQL functioning.

In addition, there are other requirements:

  • Processor with at least 1 GHz;
  • 2 gigabytes of RAM;
  • At least 512 megabytes of free disk space (more for installing additional components is recommended);
  • It is also recommended that all Windows operating system updates be installed.

Installing PostgreSQL 12 and pgAdmin 4 on Windows 10

So let’s move on to the installation process and look at all the steps that need to be followed in order to install PostgreSQL 12 and pgAdmin 4 on Windows 10.

Step 1 – Downloading the installer for Windows

As mentioned earlier, PostgreSQL is implemented for many platforms, but since we will be installing PostgreSQL on Windows, we need a Windows installer accordingly. You can of course download this distribution from the official PostgreSQL website, here is the download page – https://www.postgresql.org/download/windows/.

After going to the page you need to click on the link “Download the installer”, as a result you will be taken to the site of EnterpriseDB, which prepares graphical distributions of PostgreSQL for many platforms, including Windows, so you can immediately go to this site, here is the link to the download page https://www.enterprisedb.com/downloads/postgres-postgresql-downloads.

Here you need to select the PostgreSQL version and platform, in our case choose PostgreSQL 12 and Windows x86-64.

Downloading the installer for Windows

As a result, you should download the file postgresql-12.2-2-windows-x64.exe with the size of about 191 Mbytes (version 12.2-2 is available at the time of writing).

Step 2 – Starting the PostgreSQL installer

Now in order to start the installation you need to run the downloaded file (PostgreSQL installation requires administrator rights).

After the launch, a welcome screen will open, click “Next”.

Starting the PostgreSQL installer

Step 3 – Specify the directory to install PostgreSQL 12

Next, if necessary, we can specify the path to the directory where we want to install PostgreSQL 12, but we can leave it by default. Click “Next”.

Specify the directory to install PostgreSQL 12

Step 4 – Choose components for installation

Then select the components that we need to install, to do this we leave the checkboxes for the components that we need, and be sure we need PostgreSQL Server and pgAdmin 4.

You can install the command line utilities and Stack Builder on your own, i.e. you can not install them. Press “Next.”

Choose components for installation

Step 5 – Specify a directory to store database files

On this step, we need to specify the directory where the database files will be located by default.

In the case of a test installation, for example, for training, you can leave it by default, but “combat” databases should always be stored in a separate location, so if you plan to use the PostgreSQL server for some other purposes, it is better to specify a separate disk.

Click “Next”.

Specify a directory to store database files

Step 6 – Set a password for the postgres system user

Next we need to set a password for a postgres user – this is a PostgreSQL Server administrator with maximum rights.

We enter and confirm the password. Click “Next”.

Set a password for the postgres system user

Step 7 – Specify the port for your PostgreSQL instance

On this step, if necessary, we can change the port on which PostgreSQL Server will work, if you do not have such a need, then leave it by default.

Click “Next”.

Specify the port for your PostgreSQL instance

Step 8 – Specify the encoding in the database

Then we can specify a specific data encoding in the database, for this purpose we need to select the desired Locale from the drop-down list.

However, you can also leave it by default by clicking “Next”.

Specify the encoding in the database

Step 9 – Checking PostgreSQL installation parameters

Everything is ready for installation, at this step we check the parameters we entered earlier and if everything is correct, i.e. everything we entered, we press “Next”.

Checking PostgreSQL installation parameters

Step 10 – Start the installation process

Next you will see another additional window where we must click “Next” to start the PostgreSQL installation process on your computer.

Start the installation process

The installation has begun, it will last literally one minute.

The installation has begun

Step 11 – Finishing the installation

When the “Completing the PostgreSQL Setup Wizard” message window is displayed, the installation of PostgreSQL 12, pgAdmin 4 and other components will be completed.

Also in this window we will be offered to run Stack Builder to download and install additional components, if you do not need it, then uncheck “Lanch Stack Builder at exit?

Click “Finish”.

Finishing the installation

Run and configure pgAdmin 4

PostgreSQL 12 and pgAdmin 4 we have installed, now let’s start pgAdmin 4, connect to the server and configure the pgAdmin work environment.

To start pgAdmin 4, go to the start menu, find PostgreSQL 12 and pgAdmin 4 in it.

Connecting to the PostgreSQL 12 server

pgAdmin 4 has a web interface, so as a result you should run your browser and open the pgAdmin 4 application.

The first time you start pgAdmin 4, you will see a “Set Master Password” window, where we must set a “master password”, this may not be done, but if we save the user’s password (“Save password” checkbox), for example, so that every time you connect you do not need to enter it, it is strongly recommended to invent and specify an additional password here, it is done once.

Enter it and click “OK”.

Connecting to the PostgreSQL 12 server

To connect to the newly installed local PostgreSQL server in the server browser, click on “PostgreSQL 12”.

The “Connect to Server” window will start, where you need to enter the password of the postgres system user, i.e. this is the password that you invented when you installed PostgreSQL.

Enter the password, tick “Save Password” to save the password and each time you do not enter it (thanks to the “master password” functionality, all passwords saved in this way will be additionally encrypted).

Click on “OK”.

To connect to the newly installed local PostgreSQL server in the server browser

As a result you will connect to the local PostgreSQL 12 server and see all the objects that are located on this server.

As a result you will connect to the local PostgreSQL 12 server

In order to make sure that our PostgreSQL server is running, let’s write a simple SELECT query that will show us the PostgreSQL server version.

To write SQL queries in pgAdmin 4, you can use Query Tool or Russian “Query”, you can run it using the icon on the panel or from the menu “Tools”.

After you open the Query Tool, write.

SELECT VERSION()

This query shows the PostgreSQL version. As you can see, everything works!

How to Install PostgreSQL 12 and pgAdmin 4 on Windows 10



Tags: PostgreSQL, PostgreSQL 12, PostgreSQL data types

This is a step-by-step guide to install PostgreSQL on a windows machine. Since PostgreSQL version 8.0, a window installer is available to make the installation process fairly easier. 
We will be installing PostgreSQL version 11.3 on Windows 10 in this article. 

There are three crucial steps for the installation of PostgreSQL as follows: 

  1. Download PostgreSQL installer for Windows 
     
  2. Install PostgreSQL 
     
  3. Verify the installation 
     

Downloading PostgreSQL Installer for Windows

You can download the latest stable PostgreSQL Installer specific to your Windows by clicking here 
 

Installing the PostgreSQL installer

After downloading the installer double click on it and follow the below steps: 

  • Step 1: Click the Next button 

  • Step 2: Choose the installation folder, where you want PostgreSQL to be installed, and click on Next. 

  • Step 3: Select the components as per your requirement to install and click the Next button. 

  • Step 4: Select the database directory where you want to store the data and click on Next. 

  • Step 5: Set the password for the database superuser (Postgres) 

  • Step 6: Set the port for PostgreSQL. Make sure that no other applications are using this port. If unsure leave it to its default (5432) and click on Next. 

  • Step 7: Choose the default locale used by the database and click the Next button. 

  • Step 8: Click the Next button to start the installation. 

  • Wait for the installation to complete, it might take a few minutes. 

  • Step 9: Click the Finish button to complete the PostgreSQL installation. 

Verifying the Installation of PostgreSQL

There are couple of ways to verify the installation of PostgreSQL like connecting to the database server using some client applications like pgAdmin or psql
The quickest way though is to use the psql shell. For that follow the below steps: 
 

  • Step 1: Search for the psql shell in the windows search bar and open it. 
  • Step 2: Enter all the necessary information like the server, database, port, username, and 
    password and press Enter. 
  • Step 3: Use the command SELECT version(); you will see the following result: 
     

Last Updated :
01 Mar, 2023

Like Article

Save Article

  • Postgresql пароль по умолчанию windows
  • Postgresql открыть доступ по сети windows
  • Power media player скачать бесплатно для windows 10
  • Power dvd player for windows 10
  • Postgresql на windows как пользоваться