You are on page 1of 58

Module 3:

Lab Exercise 1
• Choose the platform on which you want to install PostgreSQL
• Download PostgreSQL one-click installer from EnterpriseDB website for
chosen platform
• Prepare the platform for installation
• Install PostgreSQL
• Connect to PostgreSQL using psql

Answer:
Windows 7 64-bit Installation
• Login as administrative user.
• Go to www.enterprisedb.com and download PostgreSQL 9.3 binaries:
• http://www.enterprisedb.com/downloads/postgres-postgresql-
downloads
• Run the binaries:

• Click yes on the User Control security dialog box and PostgreSQL
installation wizard will appear
• Follow the steps in the wizard and install PostgreSQL. Look at following
snapshots for further information:
• Maximum time to complete client authentication will be 10 seconds

Answer:
• Open a terminal:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/postgresql.conf

• Make following Changes:


max_connections = 200
superuser_reserved_connections = 10
authentication_timeout = 10s

• Save the file and close:


<Esc> :wq <Enter>

• Restart postgres cluster to implement the changes:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/scripts/serverctl.sh restart
Please enter the root password when requested.
Password:
Restarting PostgreSQL 9.3:
waiting for server to shut down.... done
server stopped
waiting for server to start.... done
server started
PostgreSQL 9.3 restarted successfully
[postgres@localhost ~]$

Lab Exercise 2
• Working as a DBA is a challenging job and to track down certain activities
on the database server logging has to be implemented. Go through server
parameters that control logging and implement following:
• Save all the error message in a file inside pg_log folder in your cluster data
directory (e.g. c:\edbdata)
• Log all queries and their time which are taking more than 5 seconds to
execute
• Log the users who are connecting to the database cluster
• Make above changes and verify them

Answer:
• Open a terminal:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/postgresql.conf

• Make following Changes:


log_directory = 'pg_log'
log_min_duration_statement = 5s
log_connections = on
• Save the file and close:
<Esc> :wq <Enter>

• Reload postgres cluster to implement the changes:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_ctl -D
/opt/PostgreSQL/9.3/data/ reload
server signaled
• Verify the changes:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql postgres postgres
Password for user postgres:
psql.bin (9.3.3)
Type "help" for help.

postgres=# show log_connections;


log_connections
-----------------
on
(1 row)

postgres=# show log_min_duration_statement;


log_min_duration_statement
----------------------------
5s
(1 row)

postgres=# show log_directory;


log_directory
---------------
pg_log
(1 row)

postgres=# \q
[postgres@localhost ~]$

Lab Exercise 3
• Perform following changes recommended by a senior DBA and verify
them:
• Shared buffer to 256MB
• Effective Cache for indexes to 512MB
• Maintenance memory to 64MB
• Temporary memory to 8MB

Answer:
• Open a terminal:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/postgresql.conf

• Make following Changes:


shared_buffers = 256MB
effective_cache_size = 512MB
maintenance_work_mem = 16MB
work_mem = 8MB

• Save the file and close:


<Esc> :wq <Enter>

• Restart postgres cluster to implement the changes:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/scripts/serverctl.sh restart
Please enter the root password when requested.
Password:
Restarting PostgreSQL 9.3:
waiting for server to shut down.... done
server stopped
waiting for server to start.... done
server started
PostgreSQL 9.3 restarted successfully
[postgres@localhost ~]$

Lab Exercise 4
• Vacuuming is important maintenance and need to be properly configured.
Change following autovacuum parameter on the production server:
• Autovacuum workers to 6
• Auto Vacuum threshhold to 100
• Auto Vacuum scale factor to 0.3
• Auto Analyze threshhold to 100
• Auto vacuum cost limit to 100

Answer:
• Open a terminal:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/postgresql.conf

• Make following Changes:


autovacuum_max_workers = 6
autovacuum_vacuum_threshold = 100
autovacuum_vacuum_scale_factor = 0.3
autovacuum_analyze_threshold = 100
autovacuum_vacuum_cost_limit = 100

• Save the file and close:


<Esc> :wq <Enter>

• Reload postgres cluster to implement the changes:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_ctl -D
/opt/PostgreSQL/9.3/data/ reload
server signaled
Module 5:
Lab Exercise - 1
• A new website is to be developed for online music store.
• Create a database user edbstore in your existing cluster
• Create a edbstore database with ownership of edbstore user
• Login inside edbstore database using edbstore user and create edbstore
schema
Answer:
• Open a Terminal and connect to postgres database with postgres user:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql postgres postgres
Password for user postgres:
psql.bin (9.3.3)
Type "help" for help.

postgres=# create user edbstore password 'edbstore';


CREATE ROLE
postgres=# create database edbstore owner edbstore;
CREATE DATABASE
postgres=# \c edbstore edbstore
Password for user edbstore:
You are now connected to database "edbstore" as user "edbstore".
edbstore=> create schema edbstore;
CREATE SCHEMA
edbstore=>\q

Lab Exercise 2
• An e-music online store website application developer wants to add
online buy/sell facility and has asked you to separate all tables used in
online transactions, here you have suggested to use schemas. Implement
following suggested options:
• Create an ebuy user with password ‘lion’
• Create an ebuy schema which can be used by ebuy user
• Login as ebuy user, create a table sample1 and check whether that table
belongs to ebuy schema or not.
Answer:
• Open a Terminal and connect to postgres database with postgres user:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql postgres postgres
Password for user postgres:
psql.bin (9.3.3)
Type "help" for help.
postgres=# create user ebuy password 'lion';
CREATE ROLE
postgres=# create schema ebuy authorization ebuy;
CREATE SCHEMA
postgres=# \c postgres ebuy
Password for user ebuy:
• Open a Terminal and copy the edbstore.sql file into home directory of
postgres user.
[root@localhost ~]# cp /home/edb/Downloads/edbstore.sql
/home/postgres/
[root@localhost ~]# chown postgres:postgres
/home/postgres/edbstore.sql
[root@localhost ~]# su - postgres
Run following command:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -f edbstore.sql -d
edbstore -U edbstore
Password for user edbstore:

Now connect to edbstore and verify the Sample database objects.


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -d edbstore -U
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.

edbstore=> \dt
List of relations
Schema | Name | Type | Owner
----------+------------+-------+----------
edbstore | categories | table | edbstore
edbstore | cust_hist | table | edbstore
edbstore | customers | table | edbstore
edbstore | dept | table | edbstore
edbstore | emp | table | edbstore
edbstore | inventory | table | edbstore
edbstore | job_grd | table | edbstore
edbstore | jobhist | table | edbstore
edbstore | locations | table | edbstore
edbstore | orderlines | table | edbstore
edbstore | orders | table | edbstore
edbstore | products | table | edbstore
edbstore | reorder | table | edbstore
(13 rows)

edbstore=> \dv
List of relations
Schema | Name | Type | Owner
----------+----------+------+----------
edbstore | salesemp | view | edbstore
(1 row)

edbstore=> \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)

edbstore=> \ds
List of relations
Schema | Name | Type | Owner
----------+--------------------------+----------+----------
edbstore | categories_category_seq | sequence | edbstore
edbstore | customers_customerid_seq | sequence | edbstore
edbstore | next_empno | sequence | edbstore
edbstore | orders_orderid_seq | sequence | edbstore
edbstore | products_prod_id_seq | sequence | edbstore
(5 rows)

edbstore=>

Lab Exercise 4
• Retrieve a list of databases using SQL Query
• Retrieve a list of databases using psql meta command.
• Retrieve a list of tables in edbstore database and check which schema and
owner they have.
Answer:
• Connect to edbstore and execute following commands:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -d edbstore -U
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=> select datname from pg_database;
datname
-----------
template1
template0
postgres
edbstore
(4 rows)

edbstore=> \l
edbstore=> \dt
List of relations
Schema | Name | Type | Owner
----------+------------+-------+----------
edbstore | categories | table | edbstore
edbstore | cust_hist | table | edbstore
edbstore | customers | table | edbstore
edbstore | dept | table | edbstore
edbstore | emp | table | edbstore
edbstore | inventory | table | edbstore
edbstore | job_grd | table | edbstore
edbstore | jobhist | table | edbstore
edbstore | locations | table | edbstore
edbstore | orderlines | table | edbstore
edbstore | orders | table | edbstore
edbstore | products | table | edbstore
edbstore | reorder | table | edbstore
(13 rows)

edbstore=> \q

Module 6:
Lab Exercise – 1
• Connect to database using psql
• Switch databases.
• Describe the customers table.
• Describe the customers table including description.
• List all databases.
• List all schemas.
• List all tablespaces.
• Execute an sql statement, saving the output to a file.
• Do the same thing, just saving data, not the column headers.
• Create a script via another method, and execute from psql.
• Turn on the expanded table formatting mode.
• Lists tables, views and sequences with their associated access privileges.
• Which meta command display SQL text for a function?
• View the current working directory.
Answer:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql postgres postgres
Password for user postgres:
psql.bin (9.3.3)
Type "help" for help.

postgres=# \c edbstore edbstore


Password for user edbstore:
You are now connected to database "edbstore" as user "edbstore".

edbstore=> \d customers

edbstore=> \d+ customers

edbstore=>\l

edbstore=>\dn

edbstore=>\db

edbstore=> \o customer_data.txt
edbstore=> select * from customers;
edbstore=> \o
edbstore=> \t
Showing only tuples.
edbstore=> \o customer_data.txt
edbstore=> select * from customers;
edbstore=> \o
edbstore=> \t
Tuples only is off.
edbstore=> \q

[postgres@localhost ~]$ vi emp.sql


select * from emp;
<esc>:wq<enter>
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -f emp.sql -d
edbstore -U edbstore
Password for user edbstore:

[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -d edbstore -U


edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=> \x
Expanded display is on.
edbstore=> select * from dept;

edbstore=> \dp

edbstore=> \df+

edbstore=> \! pwd
/home/postgres
edbstore=> \q

Module 7:
Lab Exercise - 1
• Open Pgadmin III and connect to the default PostgreSQL database cluster.
• Create a user named pguser.
• Create a database named pgdb owned by pguser.
• After creating pgdb database change its connection limit to 2.
• Create a schema named pguser inside pgdb database. Schema owner
should be pguser.
Continue to lab exercise 2

Answer:
Open Pgadmin III as shown in following snapshots:
Right Click on Login Roles and click New Login Role as show in snapshot:
Click Definition Tab:

Click ok after entering the password.

Create a database named pgdb owned by pguser


Right Click on Databases
Enter database name and Owner and Click ok.

After creating pgdb database change its connection limit to 2.


Right Click on pgdb database and click properties.
Click Definition Tab and Enter Connection Limit 2. Click ok

Create a schema named pguser inside pgdb database. Schema owner should be
pguser.
Right Click on Schemas in pgdb database and click New Schema.
Now Enter Schema Name and Owner. Click ok.

Lab Exercise - 2
• You have created pgdb database with pguser schema. Create following
objects in pguser schema:
• Table: Teams with column TeamID, TeamName, TeamRatings
• Sequence: seq_teamid start value: 1 increment by 1
• Columns: Change default value for TeamID column to seq_teamid
• Constraint: TeamRatings must be between 1 and 10
• Index: Primary Key TeamID
• View: Display all teams in ascending order of their ratings. Name the view
as vw_top_teams

Answer:
Open Pgadmin III and Expland Databases --> pgdb --> Schemas --> pguser
Right Click Tables and click New Table. Enter Table name and Owner

Click Columns tab and Click add


Enter Column Name and data type and click ok. Do this for all columns as
shown in the snapshots:
Right Click in Sequences and Click New Sequence:

Enter Sequence Name and Owner:

Click on definition tab and Enter Increment: 1 and Start: 1. Click ok.
Expan teams table-- columns and right click on teamid column. Click Properties

Click Definition tab and enter default value:


Right Click on Constraints in teams table. Go to New Object and Click New
Check

Enter Definition for Check constraint. You may skip the name as it will be
assigned by DB Server.
Right Click on Views in pguser Schema. Click New View.
Enter the name and Owner of the view.

Click definition tab and enter the body of the view. Click ok
Lab Exercise - 3
• View all rows present in teams table.
• Using the Edit data window you just opened in previous step insert
following rows in teams table
TeamID TeamName TeamRatings
Auto generated Oilers 1
Auto generated Rangers 6
Auto generated Canucks 8
Auto generated Blackhawks 5
Auto generated Bruins 2

Answers:
• Make following Changes:
listen_addresses='*'

• Save the file and close:


<Esc> :wq <Enter>

• Restart postgres cluster to implement the changes:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/scripts/serverctl.sh restart
Please enter the root password when requested.
Password:
Restarting PostgreSQL 9.3:
waiting for server to shut down.... done
server stopped
waiting for server to start.... done
server started
PostgreSQL 9.3 restarted successfully
[postgres@localhost ~]$

Lab Exercise - 2
• You are working as a PostgreSQL DBA. A developer showed you
following error:
psql: could not connect to server: Connection refused
(0x0000274D/10061)
Is the server running on host 192.168.30.22" and accepting
TCP/IP connections on port 5432?

• Predict the problem and suggest the solution

Answer:
• Open a terminal:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/pg_hba.conf

• Add following entry at the end:


host all all 192.168.30.22/32 md5

• Save the file and close:


<Esc> :wq <Enter>

• Reload postgres cluster to implement the changes:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_ctl -D
/opt/PostgreSQL/9.3/data/ reload
server signaled

Lab Exercise - 3
• A new developer has joined. His ID number is 89. Create a new user by
name dev89 and password ‘password89’. Then assign necessary privileges
to dev89 so that he can connect to the edbstore database and view all
tables.

Answer:
• Open a Terminal and login as postgres user:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql postgres postgres
Password for user postgres:
psql.bin (9.3.3)
Type "help" for help.

postgres=# create user dev89 password 'password89';


CREATE ROLE
postgres=# GRANT CONNECT ON DATABASE edbstore to dev89;
GRANT
postgres=# \c edbstore postgres
You are now connected to database "edbstore" as user "postgres".
edbstore=# GRANT USAGE ON SCHEMA edbstore to dev89;
GRANT
edbstore=# GRANT SELECT,INSERT,DELETE,UPDATE ON ALL TABLES
IN SCHEMA edbstore to dev89;
GRANT
edbstore=# \c edbstore dev89
Password for user dev89:
You are now connected to database "edbstore" as user "dev89".
edbstore=> select * from dept;
ERROR: relation "dept" does not exist
LINE 1: select * from dept;
^
edbstore=> select * from edbstore.dept;
deptno | dname | loc
--------+------------+----------
10 | ACCOUNTING | NEW YORK
20 | RESEARCH | DALLAS
30 | SALES | CHICAGO
40 | OPERATIONS | BOSTON
(4 rows)

edbstore=> \q

Lab Exercise - 4
A new developer joins e-music corp. He has ip address 192.168.30.89. He is not
able to connect from his machine to the PostgreSQL server and gets the following
error on the server
FATAL: no pg_hba.conf entry for host “1.1.1.89", user “dev89", database
“edbstore", SSL off
Configure your server so that the new developer can connect from his machine.

Answer:
• Open a terminal:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/pg_hba.conf

• Add following entry at the end:


host all all 192.168.30.89/32 md5

• Save the file and close:


<Esc> :wq <Enter>

• Reload postgres cluster to implement the changes:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_ctl -D
/opt/PostgreSQL/9.3/data/ reload
server signaled

Module 9
Lab Exercise - 1
Test your knowledge:
1. Initiate an PSQL session
2. PSQL commands access the database.
True/False
3. The following SELECT statement executes successfully:
SELECT ename, job, sal AS Salary FROM emp;

True/False
4. The following SELECT statement executes successfully:
SELECT * FROM emp;

True/False
5. There are coding errors in the following statement. Can you identify
them?

SELECT empno, ename, sal * 12 ANNUAL SALARY


FROM emp;

Answer:
1. Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>

2. True

3. True if you are connected as edbstore user

4. True if you are connected as edbstore user

5. Case sensitive Colum Headings and Column Headings with space muct be
enclosed in double quotes "
SELECT empno, ename, sal * 12 "ANNUAL SALARY"
FROM edbstore.emp;

Lab Exercise - 2
• Write a statement for following:
1. The HR department needs a report of all employees. Write a query to
display the name, department number, and department name for all
employees.
2. Create a report to display employees’ name and employee number along
with their manager’s name and manager number. Label the columns
Employee, Emp#, Manager, and Mgr#, respectively.
3. Create a report for the HR department that displays employee names,
department numbers, and all the employees who work in the same
department as a given employee. Give each column an appropriate label.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>
Execute following statemens:
1. edbstore=> select ename, emp.deptno, dname from emp join dept on
emp.deptno=dept.deptno;

2. edbstore=> select e.empno as "Emp#", e.ename as "Employee", e.mgr as


"Manager", m.ename as "Mgr#" from emp e join emp m on e.mgr=m.empno;

3. edbstore=> select ename, deptno from emp where deptno = (select deptno
from emp where ename='SMITH');

Lab Exercise - 3
1. Write a query that displays the employee number and name of all
employees who work in a department with any employee whose name
contains a E.(use subquery)
Update and delete data in the EMP table.
2. Change the name of employee 7566 to Drexler.
3. Change the salary to $1,000 for all employees who have a salary less than
$900.
4. Verify your changes to the table.
5. Delete MILLER from the EMP table.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>
Execute following statemens:
1. edbstore=> select ename, deptno from emp where deptno IN (select deptno
from emp where ename like '%E%');

2. edbstore=> UPDATE emp set ename='DREXLER' where empno=7566;

3. edbstore=> UPDATE emp set sal=1000.00 where sal<900.00;

4. edbstore=> table emp;

5. edbstore=> delete from emp where ename='MILLER';

Lab Exercise - 4
• Create the EMP2 table based on the structure of the EMP table. Include
only the empno, ename, sal, and deptno columns. Name the columns in
your new table ID, FIRST_NAME, SALARY , and DEPTID, respectively.
• The staff in the HR department wants to hide some of the data in the EMP
table. They want a view called EMPVU based on the employee numbers,
employee names, and department numbers from the EMP table. They
want the heading for the employee name to be EMPLOYEE.
• Confirm that the view works. Display the contents of the EMPVU view.
• Using your EMPVU view, write a query for the SALES department to
display all employee names and department numbers.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>
Execute following statemens:
1. edbstore=> CREATE TABLE emp2(ID, FIRST_NAME, SALARY, DEPTID) AS
select empno, ename, sal, deptno from emp;

2. edbstore=> CREATE VIEW empvu as select empno, ename as employee,


deptno from emp;
CREATE VIEW
edbstore=> \dv
List of relations
Schema | Name | Type | Owner
----------+----------+------+----------
edbstore | empvu | view | edbstore
edbstore | salesemp | view | edbstore
(2 rows)

3. edbstore=> select * from empvu;

4. edbstore=> select employee,deptno from empvu;

Lab Exercise - 5
You need a sequence that can be used with the primary key column of the dept
table. The sequence should start at 60 and have a maximum value of 200. Have
your sequence increment by 10. Name the sequence dept_id_seq.
To test your sequence, write a script to insert two rows in the dept table.
Create a index on deptno column of dept table.
Create and test a partial index.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>

edbstore=> CREATE SEQUENCE dept_id_seq start with 60 increment by


10 maxvalue 200;
edbstore=> CREATE INDEX idx_deptno ON dept(deptno);

edbstore=> \d cust_hist
Table "edbstore.cust_hist"
Column | Type | Modifiers
------------+---------+-----------
customerid | integer | not null
orderid | integer | not null
prod_id | integer | not null
Indexes:
"ix_cust_hist_customerid" btree (customerid)
Foreign-key constraints:
"fk_cust_hist_customerid" FOREIGN KEY (customerid) REFERENCES
customers(customerid) ON DELETE CASCADE

edbstore=> select min(orderid), max(orderid) from cust_hist;


min | max
-----+-------
1 | 12000
(1 row)

edbstore=> create index idx1_6000_orderid on cust_hist(orderid) where


orderid between 1 and 6000;
CREATE INDEX
edbstore=> create index idx6001_12000_orderid on cust_hist(orderid)
where orderid between 6001 and 12000;
CREATE INDEX
edbstore=> explain select * from cust_hist where orderid=5000;
QUERY PLAN
------------------------------------------------------------------------------------
Index Scan using idx1_6000_orderid on cust_hist (cost=0.00..8.34 rows=5
width=12)
Index Cond: (orderid = 5000)
(2 rows)

edbstore=> explain select * from cust_hist where orderid=10000;


QUERY PLAN
----------------------------------------------------------------------------------------
Index Scan using idx6001_12000_orderid on cust_hist (cost=0.00..8.34
rows=5 width=12)
Index Cond: (orderid = 10000)
(2 rows)

edbstore=>\q

Module 10
Lab Exercise - 1
• EDBStore website database is all setup and as a DBA you need to plan a
proper backup strategy and implement it.
• As the root user, create a folder /pgbackup and assign ownership to
Postgres user using chown utility or windows security tab in folder
properties.
• Take a full database dump of the edbstore database with the pg_dump
utility. The dump should be in plain text format.
• Name the dump file as edbstore_full.sql and store it in the /pgbackup
directory.

Answer:
Open a Terminal and login as postgres user:

[root@localhost ~]# mkdir /pgbackup


[root@localhost ~]# chown postgres:postgres /pgbackup/
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_dump -f
/pgbackup/edbstore_full.sql -U postgres edbstore
Password:
[postgres@localhost ~]$

Lab Exercise - 2
Take a dump edbstore schema from edbstore database and name the file as
edbstore_schema.sql,

Take a data-only dump of the edbstore database, disable all triggers for faster
restore, use the insert command instead of copy, and name the file as
edbstore_data.sql

Take a full dump of customers table and name the file as edbstore_customers.sql

Answer:
Open a Terminal and login as postgres user:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_dump -n
edbstore -f /pgbackup/edbstore_schema.sql -U postgres edbstore
Password:

[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_dump --inserts


--disable-triggers -f /pgbackup/edbstore_data.sql -U postgres edbstore
Password:

Lab Exercise - 3
Take a full database dump of the edbstore in compressed format using the
pg_dump utility, name the file as edbstore_full_fc.dmp

Take a full database cluster dump using pg_dumpall. Remember pg_dumpall


supports only plain text format; name the file edbdata.sql

Answer:
Open a Terminal and login as postgres user:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_dump -Fc -f
/pgbackup/edbstore_full_fc.dmp -U postgres edbstore
Password:

[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_dumpall -p 5432


-U postgres > /pgbackup/edbdata.sql
Password:
Password:
Password:
Password:
Password:

Lab Exercise - 4
In this exercise you will demonstrate your ability to restore a database.
Drop database edbstore.
Create database edbstore with owner edbstore
Restore the full dump from edbstore_full.sql and verify all the objects and their
ownership.
Drop database edbstore.
Create database edbstore with edbstore owner.
Restore the full dump from compressed file edbstore_full_fc.dmp and verify all
the objects and their ownership.

Answer:
Open a Terminal and login as postgres user:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/dropdb edbstore
Password:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/createdb -O edbstore
edbstore
Password:
[postgres@localhost ~]$ ls /pgbackup/
edbdata.sql edbstore_full_fc.dmp edbstore_schema.sql
edbstore_data.sql edbstore_full.sql
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -f
/pgbackup/edbstore_full.sql -d edbstore -U edbstore
Password for user edbstore:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -d edbstore -U edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.

edbstore=> \dt
List of relations
Schema | Name | Type | Owner
----------+------------+-------+----------
edbstore | categories | table | edbstore
edbstore | cust_hist | table | edbstore
edbstore | customers | table | edbstore
edbstore | dept | table | edbstore
edbstore | emp | table | edbstore
edbstore | emp2 | table | edbstore
edbstore | inventory | table | edbstore
.........
.........

edbstore=> \q
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/dropdb edbstore
Password:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/createdb -O edbstore
edbstore Password:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/pg_restore -d edbstore
/pgbackup/edbstore_full_fc.dmp
Password:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -d edbstore -U edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.

edbstore=> \dt
List of relations
Schema | Name | Type | Owner
----------+------------+-------+----------
edbstore | categories | table | edbstore
edbstore | cust_hist | table | edbstore
edbstore | customers | table | edbstore
edbstore | dept | table | edbstore
edbstore | emp | table | edbstore
edbstore | emp2 | table | edbstore
.........
.........

Lab Exercise - 5
• Create a directory /opt/arch or c:\arch and give ownership to Postgres
user.
• Configure your cluster to run in archive mode and archive log location to
be /opt/arch or c:\arch.
• Take a full online base backup of your cluster in /pgbackup directory
using pg_basebackup utility.

Answer:

• Open a Terminal. Connect as root user:

[root@localhost ~]# mkdir /opt/arch


[root@localhost ~]# chown postgres:postgres /opt/arch/
[root@localhost ~]# su - postgres
• Open the config file:
[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/postgresql.conf

• Change following parameters:


wal_level = archive
archive_mode = on
archive_command = 'cp %p /opt/arch/%f'
max_wal_senders = 2

• Save and close the vi editor <Esc> :wq <enter>

• Open the config file:


[postgres@localhost ~]$ vi /opt/PostgreSQL/9.3/data/pg_hba.conf
• Uncomment following entries:
local replication postgres md5
host replication postgres 127.0.0.1/32 md5
host replication postgres ::1/128 md5

• Save and close the vi editor <Esc> :wq <enter>

• Restart the server:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/scripts/serverctl.sh restart

• Take the backup


[postgres@localhost ~]$ pg_basebackup -h localhost -D /pgbackup/data

Lab Exercise - 6
• A database cluster can encounter different types of failures. Recover your
database from variety of simulated failures:
- Recover from loss of postgresql.conf file.
- Recover from loss of a emp table data file.
- Recover mistakenly dropped table cust_hist

Answer:
Recover from loss of postgresql.conf file.
Stop the database cluster:
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/scripts/serverctl.sh stop

Copy the postgresql.conf file from the backup directory location.


cp /pgbackup/data/postgresql.conf /opt/PostgreSQL/9.3/data/

Start the database cluster:


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/scripts/serverctl.sh stop

Recover from loss of a emp table data file.


You can recover the emp table from the online pg_dump backup of edbstore
database:
[postgres@localhost ~]$ psql edbstore edbstore
psql.bin (9.3.3)
Type "help" for help.

edbstore=> drop table emp;


ERROR: cannot drop table emp because other objects depend on it
DETAIL: view salesemp depends on table emp
constraint jobhist_ref_emp_fk on table jobhist depends on table emp
HINT: Use DROP ... CASCADE to drop the dependent objects too.
edbstore=> drop table emp cascade;
NOTICE: drop cascades to 2 other objects
DETAIL: drop cascades to view salesemp
drop cascades to constraint jobhist_ref_emp_fk on table jobhist
DROP TABLE
edbstore=> \q
[postgres@localhost ~]$ pg_restore -Ft -n edbstore -t emp -v -d edbstore -U
edbstore /pgbackup/edbstore.tar
pg_restore: connecting to database for restore
pg_restore: creating TABLE emp
pg_restore: restoring data for table "emp"
pg_restore: setting owner and privileges for TABLE emp
pg_restore: setting owner and privileges for TABLE DATA emp
[postgres@localhost ~]$
[postgres@localhost ~]$ psql edbstore edbstore psql.bin (9.3.3)
Type "help" for help.

edbstore=> select count(*) from edbstore.emp;


count
-------
15
(1 row)

Now recreate the foreign key constraint and the deleted view.

Recover mistakenly dropped table cust_hist


We will follow the process of PITR in order to retrieve cust_hist table. An
example can be simulated as below:
[postgres@localhost ~]$ psql edbstore edbstore
psql.bin (9.3.3)
Type "help" for help.

edbstore=> select now();


now
-------------------------------
2013-02-13 18:38:15.739808-05
(1 row)

edbstore=> drop table cust_hist;


DROP TABLE
edbstore=> \q
[postgres@localhost ~]$ cat /opt/PostgreSQL/9.3/data/postmaster.pid
2583
/opt/PostgreSQL/9.3/data
1360774982
5432
/tmp
*
5432001 5865489
[postgres@localhost ~]$ kill -9 2583
[postgres@localhost ~]$ exit
logout
[root@localhost ~]# mv /opt/PostgreSQL/9.3/data
/opt/PostgreSQL/9.3/crashdata
[root@localhost ~]# ls /opt/PostgreSQL/9.3
bin include pgAdmin3 share uninstall-postgresql.dat
crashdata installer pg_env.sh stackbuilder
doc lib scripts uninstall-postgresql
[root@localhost ~]# cp -rp /pgbackup/data/ /opt/PostgreSQL/9.3/
[root@localhost ~]# cp -p /opt/PostgreSQL/9.3/crashdata/pg_xlog/0*
/opt/PostgreSQL/9.3/data/pg_xlog/
[root@localhost ~]# vi /opt/PostgreSQL/9.3/data/recovery.conf
restore_command='cp /opt/arch/%f %p'
recovery_target_time='2013-02-13 18:38:15'

Save and Close

[root@localhost ~]# chown postgres:postgres


/opt/PostgreSQL/9.3/data/recovery.conf

Start the server:


[root@localhost ~]# /etc/init.d/postgresql-9.3 start
Starting PostgreSQL 9.3:
waiting for server to start...... done
server started
PostgreSQL 9.3 started successfully
[root@localhost ~]#

Verify if the table is recovered successfully :


[root@localhost ~]# su - postgres
[postgres@localhost ~]$ psql edbstore edbstore psql.bin (9.3.3)
Type "help" for help.

edbstore=> select count(*) from cust_hist;


count
-------
60350
(1 row)

edbstore=>
Module 11
Lab Exercise - 1
Create an explain plan for following query
Select * from emp where empno=7566;
Select * from emp where empno > 7566
Select * from emp where empno is not null

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>

edbstore=>Explain Select * from emp where empno=7566;


edbstore=>Explain Select * from emp where empno > 7566
edbstore=>Explain Select * from emp where empno is not null

Lab Exercise - 2
In previous exercise you saw that first query is not using index scan:
edbstore=> explain select * from emp where empno=7566;
QUERY PLAN
-----------------------------------------------------
Seq Scan on emp (cost=0.00..1.18 rows=1 width=146)
Filter: (empno = 7566::numeric)
(2 rows)
Write a statement in the user session forces index scan for this query.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>

edbstore=> set enable_seqscan=false;


SET
edbstore=> set enable_bitmapscan=false;
SET
edbstore=> explain select * from emp where empno=7566;
QUERY PLAN
--------------------------------------------------------------------
Index Scan using emp_pk on emp (cost=0.00..8.27 rows=1 width=146)
Index Cond: (empno = 7566::numeric)
(2 rows)

edbstore=>

Lab Exercise - 3
• Looking at the statistics you found that some tables are not automatically
maintained by autovacuum. You decided to perform manual maintenance
on some tables. Write a SQL script to perform following maintenance:
• Reclaim obsolete row space from customers table.
• Update statistics for emp and dept tables.
• Mark all the obsolete rows in orders table for reuse
• Execute the newly created maintenance script on edbstore database.

Answer:
Open a Terminal:
[postgres@localhost ~]$ vi edbstore_mnts_script.sql

VACUUM FULL customers;


ANALYZE emp;
ANALYZE dept;
VACUUM orders;

Save and close.


[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql -f
edbstore_mnts_script.sql -d edbstore -U edbstore
Password for user edbstore:
VACUUM
ANALYZE
ANALYZE
VACUUM

Lab Exercise - 4
• Composite index named ix_orderlines_orderid on (orderid, orderlineid)
columns of orderlines tables is performing very slow. Write a statement to
reindex this index for better performance.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>
edbstore=> REINDEX INDEX ix_orderlines_orderid;
REINDEX
edbstore=>\q

Module 12
Lab Exercise - 1
• You are working with different schemas in a database. After a while you
need to determine all the schemas in your search path. Write a query to
find the list of schemas currently in your search path.
Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=> select current_schemas(true);
current_schemas
------------------------------
{pg_catalog,edbstore,public}
(1 row)

edbstore=> show search_path;


search_path
----------------
"$user",public
(1 row)

edbstore=>

Lab Exercise - 2
• You need to determine the names and definitions of all of the views in
your schema. Create a report that retrieves view information: the view
name and definition text.

• After making a change in postgresql.conf file its time to reload the config
file. Write a statement in psql to reload the config file.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore
edbstore
Password for user edbstore:
psql.bin (9.3.3)
Type "help" for help.
edbstore=>
edbstore=> select * from pg_views where schemaname='edbstore';

edbstore=> \c edbstore postgres


Password for user postgres:
You are now connected to database "edbstore" as user "postgres".
edbstore=# select pg_reload_conf();
pg_reload_conf
----------------
t
(1 row)

edbstore=#

Lab Exercise - 3
Create of report of all the users who are currently connected. The report must
display total session time of all connected users.

You found a user connected to server since long time and decided to gracefully
kill its connection. Write a statement to perform this task.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres

Lab Exercise - 4
Write a query to display name and size of all the databases in your cluster. Size
must be displayed using a meaningful unit.

Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql postgres postgres
Password for user postgres:
psql.bin (9.3.3)
Type "help" for help.
postgres=# select usename,now()-backend_start as "Total Connection
Time", pid from pg_stat_activity;
usename | Total Connection Time | pid
----------+-----------------------+-------
ebuy | 19:41:56.730076 | 13079
postgres | 00:01:52.283003 | 24692
(2 rows)

postgres=# select pg_cancel_backend(13079);


pg_cancel_backend
-------------------
t
(1 row)

postgres=# select usename,now()-backend_start as "Total Connection


Time", pid from pg_stat_activity;
usename | Total Connection Time | pid
----------+-----------------------+-------
ebuy | 19:42:22.928933 | 13079
postgres | 00:02:18.48186 | 24692
(2 rows)

postgres=# select pg_terminate_backend(13079);


pg_terminate_backend
----------------------
t
(1 row)

postgres=# select usename,now()-backend_start as "Total Connection


Time", pid from pg_stat_activity;
usename | Total Connection Time | pid
----------+-----------------------+-------
postgres | 00:02:31.997722 | 24692
(1 row)

Module 13
Lab Exercise - 1
Unload emp table from edbstore schema to a csv file, with column headers and a
pipe (|) delimiter.

Create a copyemp table with same structure as emp table.

Load the csv file( from step 1) into copyemp table.


Answer:
Open a Terminal and login as postgres. Execute following command to connect
to database using PSQL:
[root@localhost ~]# su - postgres

[postgres@localhost ~]$ /opt/PostgreSQL/9.3/bin/psql edbstore


postgres
Password for user postgres:
psql.bin (9.3.3)
Type "help" for help.

edbstore=# COPY edbstore.emp to '/home/postgres/emp.csv' with csv


header;
COPY 13

edbstore=# CREATE TABLE copyemp (like edbstore.emp);


CREATE TABLE
edbstore=# copy copyemp from '/home/postgres/emp.csv' with csv
header;
COPY 13
edbstore=# table copyemp;
empno | ename | job | mgr | hiredate | sal | comm |
deptno
-------+---------+-----------+------+---------------------+---------+---------+--------
7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 00:00:00 | 1600.00 |
300.00 | 30
7521 | WARD | SALESMAN | 7698 | 1981-02-22 00:00:00 | 1250.00 |
500.00 | 30
....................................
......................
(13 rows)

You might also like