PostgreSQL Administration Lab Instructions
Version 3.6 (English Version) : Update 10 Jan 2023 by Siwat Siwarborvorn.
Lab 1 : PostgreSQL Installation
Objective : Install PostgreSQL from PostgreSQL repository.
1.1 ) Login to the lab machine using SSH and switch the user to root using the following command :
sudo su -
1.2 Install PostgreSQL by following these steps.
Note: You can execute the commands in Step 1.2.1 to 1.2.3 using “/pg-lab-install/install-
pg.sh” script.
1.2.1) Install PostgreSQL repository, using the following command:
sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-
9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
Note: Type the command above on the same line.
1.2.2 ) Run dnf command to prevent PostgreSQL installation from Redhat/Rocky Linux build-in
repository:
sudo dnf -qy module disable postgresql
1.2.3) Install Postgres package.
sudo dnf install -y postgresql15-server
Check whether the directory /usr/pgsql-15/bin has been created and verify that files have been
installed under this directory.
Lab 2 : Create a PostgreSQL Cluster Directory
Objective : Create a cluster directory to store Postgres data and attempt to start / stop Postgres server
process.
2.1) Login to the lab machine using SSH and switch the user to root using the follwing command :
sudo su -
Copyright (c) 2017-2024 Siwat Siwarborvorn
1
2.2) Create a cluster directory at /data . Then set permissions and set owner of directory to postgres
with following commands :
mkdir /data
chown postgres:postgres /data
chmod 700 /data
2.3) Initialize cluster directory by switching user to postgres.
su – postgres
Then, use initdb command to initialize the directory with the following command :
/usr/pgsql-15/bin/initdb -D /data
2.4) Start postgres service.
/usr/pgsql-15/bin/pg_ctl start -D /data
2.5) Use the followin command to check if Postgres service has started.
/usr/pgsql-15/bin/pg_ctl status -D /data
if postgres is running, output of the command will be something like :
pg_ctl: server is running (PID: 1616)
/usr/pgsql-15/bin/postgres "-D" "/data"
2.6) Stop the Postgres service using pg_ctl command as follows :
/usr/pgsql-15/bin/pg_ctl stop -D /data
Next, use the command from step 2.5) to verify if the postgres service is running.
Lab 3 : Setup PostgreSQL Start Automatically
Objective : Setup PostgreSQL service to start automatically upon booting machine and stop
automatically when machine is shutdown.
Note: If you left PostgreSQL service running in the previous lab, please stop it using “pg_ctl
stop” command as mention in step 2.6) before proceeding.
3.1) Login to the lab machine using ssh and switch user to root.
sudo su -
3.2) Edit the file using vi or nano.
Copyright (c) 2017-2024 Siwat Siwarborvorn
2
/usr/lib/systemd/system/postgresql-15.service
Modify the line begin with “Environment=PGDATA=” to the following :
Environment=PGDATA=/data
Save the change and execute the following command :
systemctl daemon-reload
3.3) Configure postgres service to start automatically by executing the command :
systemctl enable postgresql-15
3.4) Attempt to start Postgres service with the following command :
systemctl start postgresql-15
3.5) Verify if postgres is running after using command in step 4.4) by executing the command below :
systemctl status postgresql-15
As this command output, if PostgreSQL service is running, the line staring with Active: should be
display status as “active (running)” as shown in the following example:
[root@pg15-1 ~]$ systemctl status postgresql-15
● postgresql-15.service - PostgreSQL 15 database server
Loaded: loaded (/usr/lib/systemd/system/postgresql-15.service; enabled; vend>
Active: active (running) since Thu 2021-08-12 11:54:56 +07; 1min 26s ago
Docs: https://www.postgresql.org/docs/15/static/
Process: 971 ExecStartPre=/usr/pgsql-15/bin/postgresql-15-check-db-dir ${PGDA>
Main PID: 991 (postmaster)
Tasks: 9 (limit: 4927)
Memory: 35.7M
CGroup: /system.slice/postgresql-15.service
├─ 991 /usr/pgsql-15/bin/postmaster -D /data
├─1003 postgres: logger
├─1005 postgres: checkpointer
├─1006 postgres: background writer
├─1007 postgres: walwriter
├─1008 postgres: autovacuum launcher
├─1010 postgres: stats collector
└─1011 postgres: logical replication launcher
Press ‘q’ to exit and return to Linux command prompt.
3.6) Reboot Linux with reboot command :
Copyright (c) 2017-2024 Siwat Siwarborvorn
3
reboot
After the Linux server has rebooted, login and switch user to root (as step 3.1). Then use the command
as in step 3.5 to check if Postgres service get started automatically.
Lab 4 : Setup Shell Variables for PostgreSQL
Objective : Set shell variables to simplify running postgres command-line by assigning postgres
cluster directory name to PGDATA variable .
4.1) Login to the lab machine using ssh and switch user to root.
sudo su -
4.2) Switch user to postgres.
su – postgres
4.3) Modify /var/lib/pgsql/.pgsql_profile ( with dot as the first character in the
filename) using either nano or vi.
nano .pgsql_profile
-or-
vi .pgsql_profile
Next, append the following two lines to /var/lib/pgsql/.pgsql_profile
export PATH=$PATH:/usr/pgsql-15/bin
export PGDATA=/data
4.4) Logout and relogin lab machine. Then, try running ‘pg_ctl status’ command as in steps 2.5
with command name only (without path name) and without “-D /data” option.
Lab 5 : psql - Command Line Postgres Client
Objective : Learn how to use ‘psql’ to connect to Postgres servers
5.1) Login to the lab machine using ssh client and switch user to postgres.
sudo su – postgres
5.2) Connect to Postgres service using psql command (no option required).
5.3) While in psql command, use "\l" command to list databases created in this system.
Please list the database name you see : __________
5.4) Then connect the database named “postgres” using the following command :
Copyright (c) 2017-2024 Siwat Siwarborvorn
4
\c postgres
5.5 ) Check the current database you are connecting to with this command :
select current_database();
5.6) Exit from psql using ‘\q’ command to return to Linux command line.
5.7) Then execute exit command to quit from postgres account and return to previous Linux account
that you was logged into.
5.8) Question : While you are logging in lab server as Linux account other then postgres, if you want
to use psql command connect to Postgres server as in step 5.2), how to run psql command ? (What psql
options to specify while running psql ? )
___________________________________________
Lab 6 : Create, List and Drop Database
Objective : Learn how to create, list and drop databases in the PostgreSQL system.
6.1) Run psql and list existing databases. What is psql command to do that ? …..........
6.2) Create a new database named mydatabase. What command should be executed ?…….
6.3) Use psql command to list databases again. Do you see a new database created in step 6.2) ?
6.4) To drop the database created in step 6.2) What is the command to do that ?........................
Then list currently existing databases again to check if mydatabase database has been removed ?
Lab 7 : Schema Object
Objective : Learn how to manage PostgreSQL Schema in database and create tables within a Schema.
Connect to PostgreSQl using psql command and proceeded with following steps :
7.1) Create database named “testdb” and connect to it .
7.2) Create a table named ‘table1’, using the following command :
CREATE TABLE table1 (col1 int);
7.3) If you want to list the created table. What command will you use ? _________
7.4) In the ‘testdb’ database create in 7.1), create a schema named “myschema”. Then, use psql
Copyright (c) 2017-2024 Siwat Siwarborvorn
5
command to list the created schema. What is the command to do that ?
7.5) Create a new table in the schema created in step 7.4) using the followin command :
CREATE TABLE myschema.table1 (col1 int);
7.6) Then use command ‘\dt myschema.*’ to list to list the created table in 7.5)
7.7) Remove myschema schema. What command will you use ?
7.8) List schema again to check if myschema has been removed.
Lab 8 : User and Role
Objective : Learn how to create PostgreSQL users and roles.
8.1) Login to the lab machine using ssh client and switch user to postgres.
(use “sudo su – postgres” command)
8.2) Create a new PostgreSQL user named “pgadmin” with the following requirements :
◦ Assign password as "pgadminpass"
◦ Assign option as superuser
What command should be use ? .........
8.3) Use psql command to connect to postgres as the “pgadmin” user. How do you execute psql
command (and options) ? …......
Then use the following command to check which Postgres user you are using :
select current_user;
8.4) While connecting to Postgres as the pgadmin user, create a new Postgres user with the
following requirements :
• user name : user1
• password : user1pass
What is the command to create this user ? ……………………..
8.5) Exit from psql and then reconnect Postgres using psql command with user1.
Lab 9 : pg_hba.conf
Copyright (c) 2017-2024 Siwat Siwarborvorn
6
Objective : Learn how to modify pg_hba.conf file to allow and limit connections from
PostgreSQL clients
Note: We will use Postgres users named pgadmin and user1 from Lab 7.
9.1) Login (ro ssh) to lab machine and switch user to ‘postgres’ (use “sudo su – postgres”
command)
9.2) Modify /data/postgresql.conf to allow Postgres clients to connect to any IP Addresses
of Postgres Server by modifying listen_address parameters to the following :
listen_addresses = '*'
Then restart Postgres service
9.3) Modify /data/pg_hba.conf to allow Postgres clients using pgadmin account to connect
to postgres from any IP adresses, connect to any databases, and require specifing password.
Note : After modifying pg_hba.conf , you must restart or reload Postgres service.
9.4) Find the IP address beginning with 10.15. of you lab machine with the following command :
hostname -I
For example :
[pgstudent@pgadmin000 ~]$ hostname -I
104.248.151.47 10.15.0.5 10.130.0.2
From the example above, this machine has IP 10.15.0.5
9.5) Test what you did in step 9.3) Using psql command as following syntax :
psql -U pgadmin -h ip_address postgres
Substitute ip_address with IP address of you lab server obtained from step 9.4) and 127.0.0.1 .
If correct, you should be able to connect to Postgres using both IP addresses.
9.6) Create a new database named user1db.
9.7) Modify pg_hba.conf to allow connections with the following requirements :
Copyright (c) 2017-2024 Siwat Siwarborvorn
7
• Allow only user1 to connect to Postgres.
• Allow connections from IP addresses starting with 127.0 (127.0.x.x)
• Allow connections to user1db database only.
Use the following commands to verify your settings:
1) psql -U user1 -h 127.0.0.1 postgres
2) psql -U user1 -h 127.0.0.1 user1db
3) psql -U user1 -h 10.15.x.x postgres
4) psql -U user1 -h 10.15.x.x user1db
If correct, only command 2) will be able to establish a connections.
Lab 10 : Tablespace
Objective : Learn how to create a Tablespace and create tables in Tablespace.
10.1) Login or ssh to lab machine and switch user to root.
Next, create the /my_tablespace_dir directory using the following commands :
mkdir /my_tablespace_dir
chown postgres:postgres /my_tablespace_dir
10.2) Switch user to postgres (using “su – postgres”) and run the psqlcommand.
10.3) While in psql, create a new tablespace named "my_tablespace” on the directory created in
step 10.1) using the follow command:
create tablespace my_tablespace location '/my_tablespace_dir';
List the newly create tablespace with “\db” command and check if it is created in the specifed
directory.
10.4) Create lab_tbspace database and connect using the following commands :
create database lab_tbspace;
\c lab_tbspace
10.5) Create table1 table in lab_tbspace database (the default tablespace) using the command :
create table table1 (col1 int);
10.6) Create table2 table in my_tablespace tablespace in lab_tbspace database using the
Copyright (c) 2017-2024 Siwat Siwarborvorn
8
command :
create table table2 (col1 int) tablespace my_tablespace;
10.7) List the tablespace on which table1 and table2 has been created using the following
command:
select * from pg_tables where tablename like 'table%';
Examine the output of the command above and verify table and tablespace names at tablename and
tablespace columns respectively. Confirm if they were created using the command in steps 10.5 and
10.6
10.8 ) If we delete my_tablespace tablespace using this command:
drop tablespace my_tablespace;
Can we do that ? If not, why ?
Lab 11 : Copy Command
Objective : Learn how to use COPY command to import and export data from Postgres in various
formats
11.1) Login or ssh to lab machine and switch user to postgres.
11.2 ) Copy create_superstore.sql and sample_superstore.csv files from /pg-
lab-install to /var/lib/pgsql and change owner of the files using the following
commands :
cd /pg-lab-install
cp *.sql /var/lib/pgsql
cp sample_superstore.csv /var/lib/pgsql
cd /var/lib/pgsql
chown postgres:postgres sample_superstore.csv
chown postgres:postgres *.sql
11.3) Create a database named testdb with the following command :
createdb testdb
11.3) Create superstore table in testdb database with the following command :
psql -f /var/lib/pgsql/create_superstore.sql
11.4) Use the psql command connect to PostgreSQL. Then :
11.4.1) Check if the testdb database contains the superstore tables :
Copyright (c) 2017-2024 Siwat Siwarborvorn
9
\c testdb
\dt superstore
11.4.2) Count the number of records in the superstore table and note down the result.
select count(*) from superstore;
11.5) Use COPY command to load data from /var/lib/pgsql/sample_superstore.csv
and save to superstore table in testdb database.
Note: sample_superstore.csv file has csv format
What COPY command and options to use ? .....................................................
If you run the COPY command correctly , the output you should see is :
COPY 9994
11.6) Run the same command as step 11.4.2 to count the number of records in superstore table
again. How many records ? …...................
11.7) Use COPY command to export data in superstore table in text file format using the following
command :
copy superstore to '/var/lib/pgsql/sample_superstore_nohead.txt';
Note: In this step, you must specify filename with full pathname.
11.8) Exit from psql back to Linux command line. Then, check the format of data in
/var/lib/pgsql/sample_superstore_nohead.txt file with the following
command :
head /var/lib/pgsql/sample_superstore_nohead.txt
Question : What is the format of the file (text or csv) ? _____
Lab #12 : Backup and Restore
Copyright (c) 2017-2024 Siwat Siwarborvorn
10
Objective : Use pg_backup and pg_restore commands to backup and restore data from
PostgreSQL
12.1) Login Linux and switch user to postgres with command :
sudo su – postgres
12.2) Create a database named “sample_db” with the following command:
psql < sample_db.sql
12.3) Use pg_dump command to backup sample_db database to sample_db.dump file using
following command:
pg_dump -Fc -f sample_db.dump sample_db
12.4) Create ‘sample2 ‘ database :
createdb sample2
12.5) Then, restore the backup file created in 12.3) to “sample2” database
pg_restore -d sample2 sample_db.dump
12.6) Compare tables and data in sample_db and sample2 database
Question: Is the data in the tables of both databases are different ? And why ? …........…
Lab 13 : PostgreSQL Extension
Objective : Learn how to install a PostgreSQL extension in PostgreSQL extension package.
13.1) Login Linux and then switch user to root with the command :
sudo su -
13.2) Install postgresql15-contrib package if it has not been installed before with following
command :
dnf install postgresql15-contrib
13.3) Next, switch user to postgres and run psql command
Copyright (c) 2017-2024 Siwat Siwarborvorn
11
su - postgres
psql
13.4) Connect to sample2 database with c “\c sample2” command.
13.5) List currently install extensions using ‘\dx’ command. Write down the result.
13.6) In psql,install dblink extension using the command :
create extension dblink;
If install successfully, no error will be show.
13.7) Then, use '\dx’ command to list installed extension again and compare with the output from
step 13.5.
13.8 ) Connect to postgres database, using ‘\c postgres’ command.
13.9) Use '\dx’ command to list installed extension again. Do you see dblink extension ? Why ?
Lab 14 : PostgreSQL Monitoring - Read Runtime Parameters
Objective : Learn how to use PostgreSQL build-in functions to read PostgreSQL parameters and
assigned values
14.1) login Linux and switch user to postgres. Use the following commands :
sudo su - postgres
14.2) Run psql command
psql
14.3) Call current_setting() function to read the current value of shared_buffers
parameter using the command :
select current_setting('shared_buffers');
The current value of shared_buffers is _____________.
14.4) Read current shared_buffers value from pg_settings table using the command :
select name, setting, unit from pg_settings
where name='shared_buffers';
The current value is _______________.
14.5) Exit from psql with ’\q’ command.
Copyright (c) 2017-2024 Siwat Siwarborvorn
12
14.6) Read value of shared_buffers as define in /data/postgresql.conf. Compare the
value, with the value from 14.3) and 14.4).
Lab 15 : PostgreSQL Monitoring - Session Monitoring and Control
Objective : Learn about pg_stat_activity and how to use pg_cancel_backend() and
pg_terminate_backend()
15.1) In this lab, we will use ssh client (such as putty) to connect to Postgres Server with two sessions
concurrently. In each session, login and switch user to postgres using the command :
sudo su – postgres
15.2) On both sessions, run psql command:
/usr/bin/psql
15.3) In the first session, call pg_sleep() function as follows :
select pg_sleep('1000000');
In the second session, run the following query :
select datname, pid, state, query from pg_stat_activity;
The result will show many records. Find the record which has the query column as
pg_sleep('1000000'). Write down the value in pid column of this record.
pid is _________.
15.4) In the second session, cancel the postgres backend process which run pg_sleep(). Use the
command with the following syntax :
select pg_cancel_backend('pid_number');
Replace pid_number with pid value getting from 15.3)
Observe what happens to the first session running ' select pg_sleep('1000000');'
15.5) In the first session, run this query :
select pg_sleep('3000000');
Then, in the second session, run the command as follows :
select datname, pid, state, query from pg_stat_activity ;
pid value of the first session is _____
Copyright (c) 2017-2024 Siwat Siwarborvorn
13
Question: Is the pid value the same or different from the value of pg_sleep() query in step 15.3).
Why ?
15.6) In the second session, run command with the following syntax:
select pg_terminate_backend('pid_number');
Replace pid_number as the pid value obtained from 15.5). What will happen to the first session after
executing the command?
15.7) Running the query below to get pid value of the first session:
select datname, pid, state, query from pg_stat_activity;
Question: Why does the pid value of the first session change ?
Lab 16 : PostgreSQL Monitoring - pg_reload_conf()
Objective : Learn how to reload PostgreSQL configuration using pg_reload_conf() function.
16.1) At Linux command line , switch user to postgres and edit /data/postgresql.conf
sudo su – postgres
vi /data/postgresql.conf
Note: You can nano, instead of vi.
Then, modify value of work_mem to be 8MB
work_mem = 8MB
Recored the new value. Don't restart Postgres service at this step.
16.2) Run psql command :
psql
Then read current work_mem value with the following command:
select current_setting('work_mem');
Write down the current work_mem value _____.
16.3) Then, reload Postgres service with the command :
select pg_reload_conf();
Copyright (c) 2017-2024 Siwat Siwarborvorn
14
Check work_mem value again using command in 16.2) Compare the value against the value you
obtained from steps 16.2) Has the value get changed ?
Question: If we use the same steps as 16.1) to 16.3) to change the value of shared_buffers. Can
we do that ? If not , why ?
Lab 17 : PostgreSQL Monitor - Table and Database File
Objective :Learn how to use pg_relation_filepath() and pg_table_size() function
17.1) login and switch user to postgres using the following command:
sudo su – postgres
17.2) Run psql and connect to testdb database created in previous lab :
psql testdb
17.3) Find the file name storing superstore table using command :
select pg_relation_filepath('superstore');
Question : What is the filename storing this table ? ___________
17.4) Find the size of superstore table using the command :
select pg_table_size('superstore');
Question: What is the size of this table ? _________
17.5) Run this command to the get relation size of superstore.
select pg_total_relation_size('superstore');
The relation size is _________
Question: Relation size is equal to table size or not ? Why ?
17.6) Exit from psql using ‘\q’ command to return to Linux command prompt. Then, use
‘ls -l’ command to verify if the file name you obtained from step 17.3) really exists. Additionaly,
compare the size of file obtained from this step with the size from 17.4).
Copyright (c) 2017-2024 Siwat Siwarborvorn
15