How to install postgresql on windows

Summary: in this tutorial, you will step by step learn how to install PostgreSQL on your local system.

  • Install PostgreSQL on macOS
  • Install PostgreSQL on Linux

PostgreSQL was developed for UNIX-like platforms, however, it was designed to be portable. It means that PostgreSQL can also run on other platforms such as macOS, Solaris, and Windows.

Since version 8.0, PostgreSQL offers an installer for Windows systems that makes the installation process easier and faster. For development purposes, we will install PostgreSQL version 12 on Windows 10.

There are three steps to complete the PostgreSQL installation:

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

1) Download PostgreSQL Installer for Windows

First, you need to go to the download page of PostgreSQL installers on the EnterpriseDB.

Second, click the download link as shown below:

Download PostgreSQL

It will take a few minutes to complete the download.

2) Install PostgreSQL on Window step by step

To install PostgreSQL on Windows, you need to have administrator privileges.

Step 1. Double click on the installer file, an installation wizard will appear and guide you through multiple steps where you can choose different options that you would like to have in PostgreSQL.

Step 2. Click the Next button

Step 3. Specify installation folder, choose your own or keep the default folder suggested by PostgreSQL installer and click the Next button

Step 4. Select software components to install:

  • The PostgreSQL Server to install the PostgreSQL database server
  • pgAdmin 4 to install the PostgreSQL database GUI management tool.
  • Command Line Tools to install command-line tools such as psql, pg_restore, etc. These tools allow you to interact with the PostgreSQL database server using the command-line interface.
  • Stack Builder provides a GUI that allows you to download and install drivers that work with PostgreSQL.

For the tutorial on this website, you don’t need to install Stack Builder so feel free to uncheck it and click the Next button to select the data directory:

Step 5. Select the database directory to store the data or accept the default folder. And click the Next button to go to the next step:

Step 6. Enter the password for the database superuser (postgres)

PostgreSQL runs as a service in the background under a service account named postgres. If you already created a service account with the name postgres, you need to provide the password of that account in the following window.

After entering the password, you need to retype it to confirm and click the Next button:

Step 7. Enter a port number on which the PostgreSQL database server will listen. The default port of PostgreSQL is 5432. You need to make sure that no other applications are using this port.

Step 8. Choose the default locale used by the PostgreSQL database. If you leave it as default locale, PostgreSQL will use the operating system locale. After that click the Next button.

Step 9. The setup wizard will show the summary information of PostgreSQL. You need to review it and click the Next button if everything is correct. Otherwise, you need to click the Back button to change the configuration accordingly.

Now, you’re ready to install PostgreSQL on your computer. Click the Next button to begin installing PostgreSQL.

The installation may take a few minutes to complete.

Step 10. Click the Finish button to complete the PostgreSQL installation.

3) Verify the Installation

There are several ways to verify the PostgreSQL installation. You can try to connect to the PostgreSQL database server from any client application e.g.,  psql and pgAdmin.

The quick way to verify the installation is through the psql program.

First, click the psql application to launch it. The psql command-line program will display.

Second, enter all the necessary information such as the server, database, port, username, and password. To accept the default, you can press Enter.  Note that you should provide the password that you entered during installing the PostgreSQL.

Server [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:
Password for user postgres:
psql (12.3)
WARNING: Console code page (437) differs from Windows code page (1252)
         8-bit characters might not work correctly. See psql reference
         page "Notes for Windows users" for details.
Type "help" for help.

postgres=#Code language: Shell Session (shell)

Third, issue the command SELECT version(); you will see the following output:

Congratulation! you’ve successfully installed PostgreSQL database server on your local system. Let’s learn various ways to connect to PostgreSQL database server.

Was this tutorial helpful ?

In this PostgreSQL tutorial, we are diving into the realm of database management by demonstrating how to install PostgreSQL on a Windows operating system. We will follow the following steps:

  • Step 1: Download PostgreSQL
  • Step 2: Begin Installation
  • Step 3: Select Components
  • Step 4: Choose Installation Data Directory
  • Step 5: Set a Password
  • Step 6: Set the Port Number
  • Step 7: Choose the Locale
  • Step 8: Install

From the official PostgreSQL website, first download the Windows installer. The webpage can be found on Community DL Page (enterprisedb.com) as of this writing. Make sure to choose the appropriate distribution and version for your Windows.

PostgreSQL Installation on Windows Download PostgreSQL
PostgreSQL Installation on Windows Download PostgreSQL

Step 2: Begin Installation

Run the installer after downloading the file. The installation process will be walked you through by a setup wizard. To proceed, select “Next”.

Then choose the desired installation directory.

PostgreSQL Installation on Windows Download PostgreSQL Installation Directory
PostgreSQL Installation on Windows Download PostgreSQL Installation Directory

Step 3: Select Components

You will then be prompted to choose the components you want to install. I advise adding the following components to a basic installation:

  • PostgreSQL Server: The database server itself is called PostgreSQL Server.
  • pgAdmin 4: A web-based PostgreSQL management tool is pgAdmin 4. It’s excellent for visually managing your databases.
  • Command Line Tools: If you intend to connect with the database using command-line-based tools, these are helpful.
  • Stack Builder: The PostgreSQL installation package includes the Stack Builder, which acts as a master installer for any extra packages you might want when using PostgreSQL.
PostgreSQL Installation on Windows Download PostgreSQL Select Components
PostgreSQL Installation on Windows Download PostgreSQL Select Components

Step 4: Choose Installation Data Directory

The data installation directory for PostgreSQL is then yours to choose. For most users, the default directory should be acceptable. Select what you want, then click “Next”.

PostgreSQL Installation on Windows Download PostgreSQL Choose Installation Data Directory
PostgreSQL Installation on Windows Download PostgreSQL Choose Installation Data Directory

Step 5: Set a Password

This action must be taken. The ‘postgres’ user, a superuser account in PostgreSQL, is having its password changed. Make a strong password choice and store it securely. To access the database, you must have this password. After entering your password, select “Next”.

PostgreSQL Installation on Windows Download PostgreSQL Set Password
PostgreSQL Installation on Windows Download PostgreSQL Set Password

Step 6: Set the Port Number

PostgreSQL’s standard port is 5432. Unless there is a problem with other applications or you have unique requirements, you’re usually fine leaving this at the default level. To proceed, click “Next”.

PostgreSQL Installation on Windows Download Set the Port Number
PostgreSQL Installation on Windows Download Set the Port Number

Step 7: Choose the Locale

You should generally leave the locale set to its default value. This will control your database’s language, sort order, and date format, among other things. Click “Next” once you have chosen your choice.

PostgreSQL Installation on Windows Download Choose the Locale
PostgreSQL Installation on Windows Download Choose the Locale

Step 8: Install

You can now begin installing PostgreSQL! The installation will start after pressing the “Next” button. Please feel free to get a cup of coffee because this could take a little while.

PostgreSQL Installation on Windows Download PostgreSQL Install
PostgreSQL Installation on Windows Download PostgreSQL Install

You see the Ready to Install wizard, then click on the “Next” button.

PostgreSQL Installation on Windows Download PostgreSQL Ready to Install
PostgreSQL Installation on Windows Download PostgreSQL Ready to Install

You will see the install progress wizard as shown in the below picture.

PostgreSQL Installation on Windows Download Installing
PostgreSQL Installation on Windows Download Installing

Step 9: Completing the Installation

The wizard will show a final screen after the installation is finished. Make sure the option to start Stack Builder when you quit is not selected (unless you want to add further drivers or tools). To end the wizard, click “Finish”.

Congratulations! PostgreSQL has been successfully installed on Windows.

PostgreSQL Installation on Windows Download Completing the Installation
PostgreSQL Installation on Windows Download Completing the Installation

You can launch the pgAdmin 4 utility from your list of installed programs to check the installation.

PostgreSQL Installation on Windows Download Opening pgAdmin
PostgreSQL Installation on Windows Download Opening pgAdmin

Your chosen “postgres” user password from the installation process will be required. If everything was installed properly, you ought to be able to connect to the PostgreSQL server and begin building databases.

PostgreSQL Installation on Windows Download Opening Checking pgAdmin
PostgreSQL Installation on Windows Download Opening Checking pgAdmin

Conclusion

In this PostgreSQL tutorial, we’ve walked you through the steps to install PostgreSQL on your Windows machine. Now, you’re ready to dive into the world of SQL and start managing your data.

You may like to read:

  • PostgreSQL installation on Linux step by step
  • What is PostgreSQL [Features & Disadvantages]
  • How to Connect PostgreSQL Databases on Linux

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

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


Posted:
30 May, 23


Updated:
29 Jun, 23



by Susith Nonis



7 Min

How to Install PostgreSQL on Windows, Mac, and Linux

List of content you will read in this article:

PostgreSQL is a popular open-source relational database management system (RDBMS) widely used by developers and businesses. Whether you’re a developer looking to create powerful data-driven applications or an organization looking to manage large amounts of data, PostgreSQL is an excellent choice. This article will guide you through installing PostgreSQL on Windows, macOS, and Linux. So, if you’re ready to start with PostgreSQL, let’s dive in!

What Is PostgreSQL?

PostgreSQL is a powerful open-source relational database management system (RDBMS) known for its robustness, scalability, and high performance. It works by storing data in tables, which are organized into schemas. Each table contains rows and columns, with each column representing an attribute of the data being stored. PostgreSQL uses SQL (Structured Query Language) to manipulate table data. SQL provides a standard way to communicate with the database and is widely used for data retrieval and manipulation.

PostgreSQL also incorporates advanced features such as queries that support advanced indexing and partitioning, allowing developers to retrieve data from large datasets efficiently. Additionally, the system supports a wide range of programming languages and frameworks, making it a versatile and flexible choice for developers working on various projects. With its strong emphasis on reliability, security, and data integrity, PostgreSQL has become a popular choice for businesses and organizations that must manage large amounts of data.

How to Install PostgreSQL on Windows

Installing PostgreSQL on Windows is a straightforward process that can be completed in just a few simple steps. Here’s a step-by-step guide to help you get started:

  1. Download the PostgreSQL installer from the official website. 
  2. Once the download is complete, run the installer by double-clicking on the downloaded file.
  3. The first screen that appears is the PostgreSQL Setup Wizard. Click «Next» to proceed.
  4. On the next screen, review the license agreement, then click «Next» to accept the terms and conditions.
  5. The following screen allows you to choose the installation directory. We recommend using the default directory unless you have a specific reason to change the installation directory. Click «Next» to proceed.
  6. On the next screen, you will be asked to choose the components to install. We recommend leaving all the checkboxes selected unless you need to change the components. Click «Next» to proceed.
  7. The next screen asks you to choose the PostgreSQL data directory. By default, this is set to C:\Program Files\PostgreSQL\\data. We recommend using the default setting unless you need to change the data directory. Click «Next» to proceed.
  8. On the next screen, you will be asked to create a password for the PostgreSQL superuser (postgres). Enter a strong password, then click «Next» to proceed.
  9. The next screen will ask you to choose the port number that PostgreSQL will use. Unless you have a specific reason to change the port number, we recommend using the default setting (5432). Click «Next» to proceed.
  10. On the next screen, review the installation summary, then click «Next» to start the installation.
  11. Once the installation is complete, click «Finish» to close the wizard.

Congratulations! You have now installed PostgreSQL on your Windows machine. You can now start using PostgreSQL by launching pgAdmin, which should be installed along with PostgreSQL.

How to Install PostgreSQL on macOS

To install PostgreSQL on macOS, you’ll need to use the Terminal app, but the process is as easy as copying and running a few commands:

  • Open the Terminal application on your Mac.
  • Install Homebrew on your Mac by running the following command: 

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  • Once Homebrew is installed, update it by running the command:

brew update

  • Install PostgreSQL by running the command:

brew install postgresql

  • After installing PostgreSQL, you can start the database server by running the command:

pg_ctl -D /usr/local/var/postgres start

  • To test if PostgreSQL is working correctly, open psql by running the command:

psql

  • You should see a prompt that looks like this:

psql (12.2)

Type "help" for help.

  • You can test that PostgreSQL is working by creating a test database by running the following command in the psql prompt:

CREATE DATABASE testdb;

  • You can list all the databases by running the command:

\list

  • When you are finished working with PostgreSQL, you can stop the database server by running the command:

pg_ctl -D /usr/local/var/postgres stop

Congratulations! You have successfully installed PostgreSQL on your Mac.

How to Install PostgreSQL on Linux

Like macOS, Linux requires you to run a few terminal commands to install PostgreSQL. Here’s how:

Here is a step-by-step guide on how to install PostgreSQL on Linux:

  • Open a terminal prompt.
  • Update the package list by running the following command:

sudo apt-get update

  • Install PostgreSQL by running the command:

sudo apt-get install postgresql postgresql-contrib

  • PostgreSQL should start automatically after installation. If it doesn’t start, run the following command to start it:

sudo service postgresql start

  • PostgreSQL is secure by default, so the default user «postgres» is the only user that can access the database. To access the PostgreSQL prompt, you will need to switch to this user using the following command:

sudo -i -u postgres

  • From here, you can start the PostgreSQL command prompt by typing:

psql

  • Create a new user account by typing:

CREATE USER myusername WITH PASSWORD 'mypassword';

  • Create a new database by typing:

CREATE DATABASE mydatabase;

  • Grant the new user full access to the new database by typing:

GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myusername;

  • Quit the PostgreSQL prompt by typing:

\q

Congratulations! You have successfully installed and configured PostgreSQL on your Linux machine.

Wrapping Up

In conclusion, installing PostgreSQL on Windows, Mac, and Linux can be a straightforward and seamless process with the right guidance. Following the step-by-step guides provided for each operating system, users can successfully download, install, and configure PostgreSQL to meet their database needs. With PostgreSQL’s versatility, security, and scalability, users can use its features for various applications, from small-scale projects to large-scale enterprise-level operations. Whether you are a developer or a business owner, PostgreSQL can be a valuable tool in managing and processing data, and installing it on your desired operating system is the first step toward utilizing its benefits.

  • PostgreSQL is a popular open-source relational database management system that runs on Windows, Mac, and Linux.
  • Installing PostgreSQL on these operating systems involves downloading the installer and following the steps in the installation wizard.
  • Users can install PostgreSQL on Windows using the graphical installer or the command-line installer.
  • PostgreSQL can be installed on Mac using the Homebrew package manager or by downloading the installer from the official website.
  • On Linux, users can install PostgreSQL from the default package manager or download the installer from the official website.

People also read:

  • Exploring PostgreSQL Port
  • Installing PostgreSQL on CentOS
  • What Is the Default Postgres Password

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

  • How to install pip python on windows
  • How to install windows installer
  • How to install windows os on mac os
  • How to install openjdk on windows
  • How to install windows from ubuntu