Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

PostgreSQL Tutorial

Welcome to the PostgreSQLTutorial.com website! This PostgreSQL tutorial


helps you understand PostgreSQL quickly. You’ll master PostgreSQL very fast
through many practical examples and apply the knowledge in developing
applications using PostgreSQL.

If you are…

Looking for learning PostgreSQL fast.

Developing applications using PostgreSQL as the back-end database management system.

Migrating from other database management systems such as MySQL, Oracle, Microsoft SQL
Server to PostgreSQL.

You’ll find all you need to know to get started with PostgreSQL quickly and effectively here on
this website.

PostgreSQL tutorial demonstrates many unique features of PostgreSQL that make it the most
advanced open-source database management system.

Getting Started with PostgreSQL


(https://www.postgresqltutorial.com/postgresql-getting-started/)

This section helps you get started with PostgreSQL by showing you how
to install PostgreSQL on Windows, Linux, and macOS. You also learn how
to connect to PostgreSQL using the psql tool as well as how to load a
sample database into the PostgreSQL for practicing.

Basic PostgreSQL Tutorial

First, you’ll learn how to query data from a single table using basic data querying techniques,
including selecting data, sorting result sets, and filtering rows. Then, you’ll learn about advanced
queries such as joining multiple tables, using set operations, and constructing the subquery.
Finally, you will learn how to manage database tables, such as creating a new table or modifying
an existing table’s structure.
Advanced PostgreSQL Tutorial

This advanced PostgreSQL tutorial covers the advanced concepts including stored procedures,
indexes, views, triggers, and database administrations.

PostgreSQL PL/pgSQL (https://www.postgresqltutorial.com


/postgresql-plpgsql/)

This PostgreSQL stored procedures section shows you step by step how
to develop PostgreSQL user-defined functions using PL/pgSQL
procedural language.

PostgreSQL Triggers (https://www.postgresqltutorial.com


/postgresql-triggers/)

This section provides you with PostgreSQL trigger concept and shows
how to manage triggers in PostgreSQL.

PostgreSQL Views (https://www.postgresqltutorial.com


/postgresql-views/)

We will introduce you to the database views concept and show you how
to manage views such as create, alter, and remove views from the
database.

PostgreSQL Indexes (https://www.postgresqltutorial.com


/postgresql-indexes/)

PostgreSQL indexes are effective tools to enhance database


performance. Indexes help the database server find specific rows much
faster than it could do without indexes.
PostgreSQL Administration
(https://www.postgresqltutorial.com/postgresql-administration/)

PostgreSQL administration covers the most important activities for


PostgreSQL database server including roles and databases management,
backup and restore.
PostgreSQL Sample Database

Summary: in this tutorial, we will introduce you to a PostgreSQL sample database that you can
use for learning and practice PostgreSQL.

We will use the DVD rental database for demonstrating the features of PostgreSQL.

The DVD rental database represents the business processes of a DVD rental store. The DVD
rental database has many objects including:

15 tables

1 trigger

7 views

8 functions

1 domain

13 sequences

DVD Rental ER Model


PostgreSQL Sample Database Tables

There are 15 tables in the DVD Rental database:


actor – stores actors data including first name and last name.

film – stores film data such as title, release year, length, rating, etc.

film_actor – stores the relationships between films and actors.

category – stores film’s categories data.

film_category- stores the relationships between films and categories.

store – contains the store data including manager staff and address.

inventory – stores inventory data.

rental – stores rental data.

payment – stores customer’s payments.

staff – stores staff data.

customer – stores customer data.

address – stores address data for staff and customers

city – stores city names.

country – stores country names.

Download PostgreSQL sample database

You can download the PostgreSQL DVD Rental sample database via the following link:

Download DVD Rental Sample Database (https://www.postgresqltutorial.com/wp-content/uploads/2019/05


/dvdrental.zip)

The database file is in zip format ( dvdrental.zip ) so you need to extract it to 
dvdrental.tar before loading the sample database into the PostgreSQL database server

(https://www.postgresqltutorial.com/load-postgresql-sample-database/) .

Download printable ER diagram

Besides the sample database, we also provide you with a printable ER diagram in PDF format.
You can download and print the ER diagram for reference while practicing with PostgreSQL.

Download the Printable ER Diagram (https://www.postgresqltutorial.com/wp-content/uploads/2018/03


/printable-postgresql-sample-database-diagram.pdf)
This tutorial introduced you to a PostgreSQL sample database named DVD rental. We will use
this database in our PostgreSQL tutorials so make sure that you have it on your server.
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 (https://www.postgresqltutorial.com/install-postgresql-macos/)

Install PostgreSQL on Linux (https://www.postgresqltutorial.com/install-postgresql-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
(https://www.enterprisedb.com/downloads/postgres-postgresql-downloads) .

Second, click the download link as shown below:


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 (https://www.postgresqltutorial.com/connect-to-postgresql-database/) 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=#
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 (https://www.postgresqltutorial.com
/connect-to-postgresql-database/) .
Connect To a PostgreSQL Database Server

Summary: in this tutorial, you will learn how to connect to the PostgreSQL Database Server
via an interactive terminal program called psql and via the pgAdmin application.

When you installed the PostgreSQL database server (https://www.postgresqltutorial.com/install-postgresql/)


, the PostgreSQL installer also installed some useful tools for working with the PostgreSQL
database server. In this tutorial, you will learn how to connect to the PostgreSQL database server
via the following tools:

psql – a terminal-based front-end to PostgreSQL database server.

pgAdmin – a web-based front-end to PostgreSQL database server.

1) Connect to PostgreSQL database server using psql

psql is an interactive terminal program provided by PostgreSQL. It allows you to interact with the
PostgreSQL database server such as executing SQL statements and managing database objects.

The following steps show you how to connect to the PostgreSQL database server via the psql
program:

First, launch the psql program and connect to the PostgreSQL Database Server using the
postgres user:
Second, enter all the information such as Server, Database, Port, Username, and Password. If you
press Enter, the program will use the default value specified in the square bracket [] and move
the cursor to the new line. For example, localhost is the default database server. In the step
for entering the password for user postgres, you need to enter the password the user postgres
that you chose during the PostgreSQL installation (https://www.postgresqltutorial.com/install-postgresql/) .

Third, interact with the PostgreSQL Database Server by issuing an SQL statement. The following
statement returns the current version of PostgreSQL:

SELECT version();
Please do not forget to end the statement with a semicolon (;). After pressing Enter, psql will
return the current PostgreSQL version on your system.

2) Connect to PostgreSQL database server using pgAdmin

The second way to connect to a database is by using a pgAdmin application. The pgAdmin
application allows you to interact with the PostgreSQL database server via an intuitive user
interface.

The following illustrates how to connect to a database using pgAdmin GUI application:

First, launch the pgAdmin application.


The pgAdmin application will launch on the web browser as shown in the following picture:

Second, right-click the Servers node and select Create > Server… menu to create a server

Third, enter the server name e.g., PostgreSQL and click the Connection tab:
Fourth, enter the host and password for the postgres user and click the Save button:
Fifth, click on the Servers node to expand the server. By default, PostgreSQL has a database
named postgres as shown below:
Sixth, open the query tool by choosing the menu item Tool > Query Tool or click the lightning
icon.

Seventh, enter the query in the Query Editor, click the Execute button, you will see the result of
the query displaying in the Data Output tab:

Connect to PostgreSQL database from other applications

Any application that supports ODBC or JDBC (https://www.postgresqltutorial.com/postgresql-jdbc/) can


connect to the PostgreSQL database server. In addition, if you develop an application that uses a
specific driver, the application can connect to the PostgreSQL database server as well:

Connect to PostgreSQL from PHP (https://www.postgresqltutorial.com/postgresql-php/connect/)

Connect to PostgreSQL from Python (https://www.postgresqltutorial.com/postgresql-python/connect/)

Connect to PostgreSQL from Java (https://www.postgresqltutorial.com/postgresql-jdbc/connecting-to-


postgresql-database/)

In this tutorial, you’ve learned how to connect to the PostgreSQL database server by using
different client tools including psql and pgAdmin GUI application.
Load PostgreSQL Sample Database

Summary: in this tutorial, we will show you how to load the PostgreSQL sample database into
the PostgreSQL database server.

Before going forward with this tutorial, you need to have:

A PostgreSQL database server installed on your system.

A PostgreSQL sample database (https://www.postgresqltutorial.com/postgresql-sample-database/) called


dvdrental.

Load the sample database using psql tool

First, launch the psql tool.

>psql

Second, enter the account’s information to log in to the PostgreSQL database server. You can
use the default value provided by psql by pressing the Enter keyboard. However, for the
password, you need to enter the one that you provided during PostgreSQL installation
(https://www.postgresqltutorial.com/install-postgresql/) .

Server [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:
Password for user postgres:

Third, enter the following CREATE DATABASE (https://www.postgresqltutorial.com/postgresql-create-

database/) statement to create a new dvdrental database.

postgres=# CREATE DATABASE dvdrental;


CREATE DATABASE

PostgreSQL will create a new database named dvdrental .

Finally, enter the exit command to quit psql:

postgres=# exit

Then, navigate the bin folder of the PostgreSQL installation folder:

C:\>cd C:\Program Files\PostgreSQL\12\bin

After that, use the pg_restore tool to load data into the dvdrental database:

pg_restore -U postgres -d dvdrental C:\sampledb\dvdrental.tar

In this command:

The -U postgres specifies the postgres user to login to the PostgreSQL database server.

The -d dvdrental specifies the target database to load.

Finally, enter the password for the postgres user and press enter

Password:

It takes about seconds to load data stored in the dvdrental.tar file into the
dvdrental database.

Load the DVD Rental database using the pgAdmin

The following shows you step by step on how to use the pgAdmin tool to restore the sample
database (https://www.postgresqltutorial.com/postgresql-sample-database/) from the database file:

First, launch the pgAdmin tool and connect to the PostgreSQL server
(https://www.postgresqltutorial.com/postgresql-python/connect/) .
Second, right click the Databases and select the Create > Database… menu option:

Third, enter the database name dvdrental and click the Save button:
You’ll see the new empty database created under the Databases node:
Fourth, right-click on the dvdrental database and choose Restore… menu item to restore the
database from the downloaded database file:

Fifth, enter the path to the sample database file e.g., c:\sampledb\dvdrental.tar and click the
Restore button:
Sixth, the restoration process will complete in few seconds and shows the following dialog once
it completes:

Finally, open the dvdrental database from object browser panel, you will find tables in the
public schema and other database objects as shown in the following picture:

In this tutorial, you have learned how to load the dvdrental sample database into the
PostgreSQL database server for practicing PostgreSQL.
Install PostgreSQL macOS

Summary: in this tutorial, you will learn how to download the PostgreSQL, install PostgreSQL on
macOS, and restore the sample database.

Download PostgreSQL installer for macOS

To download the PostgreSQL installer, you follow these steps:

First, visit the PostgreSQL installer download page (https://www.enterprisedb.com/downloads


/postgres-postgresql-downloads) .

Then, download the PostgreSQL for macOS.

Install PostgreSQL on macOS

To install PostgreSQL on macOS, you follow these steps:

First, launch the setup wizard by double-click the installer file:


Second, select the directory where the PostgreSQL will be installed and click the Next button:

Third, select the components that you want to install, uncheck the Stack Builder, and click the
Next button:
Fourth, specify a directory where PostgreSQL stores the data and click the Next button:

Fifth, enter the password for the postgres user account. You should note down this password for
logging in to the PostgreSQL database server later. After that, click the Next button.
Sixth, specify the port number on which the PostgreSQL server will listen. By default, PostgreSQL
uses port number 5432.

Seventh, select the locale used by PostgreSQL. By default, PostgreSQL uses the locale of the
current operating system:
Eighth, review the installation information. If everything looks correct, click the Next button to
begin the installation.

Ninth, click the Next button to start installing the PostgreSQL database server on your computer:
It will take few mintues to complete the installation.

Finally, click the Finish button once the installation is completed:


Load the sample database

First, launch pgAdmin from Launchpad.

Second, enter the password for the postgres user.

Third, right-click the PostgreSQL 12 and select Create > Database.. to open a dialog for creating
a new database.
Fourth, enter dvdrental as the database, postgres as the owner, and click the Save button to
create the dvdrental database.
Sixth, download the sample database (https://www.postgresqltutorial.com/postgresql-sample-database/) and
unzip it. You’ll get a directory with many files.

Seventh, right-click the dvdrental database and select the Restore… menu item:
Eighth, select the directory as the Format (1), the directory that contains sample database as the
Filename (2), and postgres as the Role name (3), and click the Restore button.

It will take few seconds to restore the sample database. Once the restoration completes, you will
see a notification like this:
It means that you have successfully created the sample database and restored it from the
downloaded file.

In this tutorial, you have learned how to download PostgreSQL installer for macOS, how to install
PostgreSQL on macOS, and how to restore the sample database…
Install PostgreSQL Linux

Summary: in this tutorial, you will learn how to download and install PostgreSQL on Linux.

Most Linux platforms such as Debian, Red Hat / CentOS, SUSE, and Ubuntu have PostgreSQL
integrated with their package management.

It is recommended that you install PostgreSQL this way since it ensures a proper integration with
the operating system including automatic patching and other update management functionality.

To download and install PostgreSQL on Linux, you visit the download page
(https://www.postgresql.org/download/linux/) and select your Linux distribution.

In this tutorial, we’ll show you how to install PostgreSQL on Ubuntu 20.04.

Install PostgreSQL on Ubuntu

Once visiting the PostgreSQL download for Ubuntu page (https://www.postgresql.org/download/linux


/ubuntu/) , you find the script that allows you to install PostgreSQL on Ubuntu. You need to
execute them one by one

First, execute the following command to create the file repository configuration:

$ sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_releas

Second, import the repository signing key:

$ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sud

Third, update the package list:

$ sudo apt-get update


Finally, install the latest version of PostgreSQL:

$ sudo apt-get install postgresql

If you want to install a specific version, you can use postgresql-version instead of
postgresql . For example, to install PostgreSQL version 12, you use the following command:

$ sudo apt-get install postgresql-12

It will take few minutes to download and install the PostgreSQL.

Connect to the PostgreSQL database server via psql

In PostgreSQL, a user account is referred to as a role (https://www.postgresqltutorial.com/postgresql-roles/)


. By default, PostgreSQL uses ident authentication.

It means that PostgreSQL will associate its roles with the system accounts of Linux. If a role exists
in PostgreSQL, the same Linux user account with the same name is able to log in as that role.

When you installed PostgreSQL, the installation process created a user account called postgres
associated with the default postgres role.

To connect to PostgreSQL using the postgres role, you switch over to the postgres account
on your server by typing:

$ sudo -i -u postgres

It’ll prompt for the password of the current user. You need to provide the password and hit the
Enter keyboard.

Then, you can access the PostgreSQL using the psql by typing the following command:

$ psql

You’ll access the postgres prompt like this:


postgres=#

From here, you can interact with the PostgreSQL like issuing a query.

To quit the PostgreSQL prompt, you run the following command:

postgres=# \q

This above command will bring you back to the postgres Linux command prompt.

postgres@ubuntu-dev:~$

To return to your regular system user, you execute the  exit  command like this:

postgres@ubuntu-dev:~$ exit

Load the sample database

To load the sample database into the PostgreSQL database server, you follow these steps:

First, switch over the postgres account using the following command:

$ sudo -i -u postgres

It’ll prompt you for the password of the current user. You need to type the password of the
current user and press the Enter keyboard.

Second, download the sample database using the curl tool:

$ curl -O https://sp.postgresqltutorial.com/wp-content/uploads/2019/05/dvdre

Third, unzip the dvdrental.zip file to get the dvdrental.tar file:

$ unzip dvdrental.zip
Fourth, access the PostgreSQL using the psql tool:

$ psql

Fifth, create the dvdrental database using the CREATE DATABASE


(https://www.postgresqltutorial.com/postgresql-create-database/) statement:

postgres=# create database dvdrental;

Sixth, quit the psql by using the \q command:

postgres=# \q

Seventh, use the pg_restore tool to restore (https://www.postgresqltutorial.com/postgresql-restore-


database/) the dvdrental database:

$ pg_restore --dbname=dvdrental --verbose dvdrental.tar

Eighth, access PostgreSQL database server again using psql :

$ psql

Ninth, switch to the dvdental database:

postgres=# \c dvdrental

Now, you’re connected to the dvdrental database:

dvdrental=#

Finally, enter the following command to get the number of films in the film table:

dvdrental=# select count(*) from film;


Here is the output:

count
-------
1000
(1 row)

Congratulations! you have successfully installed PostgreSQL on Ubuntu, connect to PostgreSQL


database server using psql, and load the sample database.

You might also like