Course
Postgree SQL
Database
Introduction
• Name
• Expectations for the course
Objectives
• This course provides students with the knowledge and
skills necessary to design and implement a Postgre SQL
database.
• This course cover from basic database structure as
well as introduction to SQL up to how to design a
corporate database application using Postgre SQL.
Who Should Attend
• Database Administrator
• Hardware and Software Engineer
• Analyst and Database Designer
Course Objectives
By the end of this course, participants are able to:
• Understand basic concept of Postgre database
• Understand how to use and build database
• Perform table manipulation and maintain data
integrity
• Build Postgre -based application using SQL language
Course Outline
• Module 1 : Client-Server Programming Introduction to Postgre
• Module 2 : ERD & Database Design
• Module 3 : Postgre Client
• Module 4 : Building Database
• Module 5 : Postgre Table
• Module 6 : Writing SELECT Queries
• Module 7 : Querying Multiple Tables
• Module 8 : Grouping and Aggregating Data
• Module 9 : Using Subqueries
• Module 10 : Using Set Operators
• Module 11 : Functions
Module 1
Client-Server Programming
Introduction to Postgre
What Is PostgreSQL?
• PostgreSQL is an object-relational database management
system (ORDBMS) based on POSTGRES, Version 4.2
• PostgreSQL is an open-source descendant of this original
Berkeley code
• It supports a large part of the SQL standard and offers
many modern features:
❑ complex queries
❑ foreign keys
❑ triggers
❑ updatable views
❑ transactional integrity
❑ multiversion concurrency control
RDBMS and ORDBMS
RDBMS ORDBMS
ORDBMS that is similar to RDBMS but
A database management system base
with an object oriented database
on the relational model of data
mode
RDBMS stands for Relational Database ORDBMS stands for Object Relational
Management System Database Management System
ORDBMS is based on the Relational as
RDBMS is based on Relational data
well as Object Oriented database
model
model
RDBMS is suitable for traditional
ORDBMS is suitable for applications
application tasks such as for data
with complex objects
administration and processing
MS SQL server, MySQL, SQLite,
PostgreSQL is an ORDBMS
MariaDB are examples for RDBMS
Server programming support
PostgreSQL officially supports a few languages for
writing database functions.
• PL/pgSQL
• PL/Tcl
• PL/Perl
• PL/Python
Data Types
PostgreSQL has built-in support for general-
purpose data types. Among the most commonly
used types are:
• Numeric (integer, float, serial etc)
• Character (varying character, text)
• Date/Time (timestamp, date, time etc)
• Boolean (true, false)
• Geometry (Point, Line, Box etc)
• UUID (generating unique IDs)
• JSON (for document storage)
PostgreSQL Clients
Postgres follows the Client Server architecture
where the server listens to requests from the client
and returns a response.
Postgres can be connected from
• programming language
• CLI tool
• GUI
PostgreSQL Clients (continued)
Some of the popular client applications for
PostgreSQL include
• pg_dump - Extracting database into a file
• pg_restore - Restoring a database from a file
• create_db - Create a new PostgreSQL database
• create_user - Create a new PostgreSQL user account
• psql - Interactive terminal
The full list of client applications is available
• [Link]
[Link]
Services the Database Server
• To start the database server
pg_ctl -D "C:\Program Files\PostgreSQL\15\data" start
• To stop the database server
pg_ctl -D "C:\Program Files\PostgreSQL\15\data" stop
• To restart the database server
pg_ctl -D "C:\Program Files\PostgreSQL\15\data" restart
• To check the database server Status
pg_ctl -D "C:\Program Files\PostgreSQL\15\data" status
Services the Database Server (continued)
Another way:
• Open Run Window by Winkey + R
• Type [Link]
• Search Postgres service based on version installed.
• Click stop, start or restart the service option.
Module 2
ER model Concept
ER model
• ER model stands for an Entity-Relationship model. It is a high-level
data model. This model is used to define the data elements and
relationship for a specified system.
• It develops a conceptual design for the database. It also develops a
very simple and easy to design view of data.
• In ER modeling, the database structure is portrayed as a diagram
called an entity-relationship diagram.
Component of ER Diagram
Entity
• An entity may be any object, class, person or place.
• In the ER diagram, an entity can be represented as rectangles.
Entity - Weak Entity
• An entity that depends on another entity called a weak entity.
• The weak entity doesn't contain any key attribute of its own.
• The weak entity is represented by a double rectangle.
Attribute
• The attribute is used to describe the property of an entity.
• Eclipse is used to represent an attribute.
Attribute - Key Attribute
• The key attribute is used to represent the main characteristics of an
entity.
• It represents a primary key.
• The key attribute is represented by an ellipse with the text underlined.
Attribute - Composite Attribute
• An attribute that composed of many other attributes is known as a
composite attribute.
• The composite attribute is represented by an ellipse, and those ellipses
are connected with an ellipse.
Attribute - Multivalued Attribute
• An attribute can have more than one value.
• These attributes are known as a multivalued attribute.
• The double oval is used to represent multivalued attribute.
Attribute - Derived Attribute
• An attribute that can be derived from other attribute is known as a
derived attribute. It can be represented by a dashed ellipse.
Relationship
• A relationship is used to describe the relation between entities.
• Diamond or rhombus is used to represent the relationship.
Relationship - One-to-One Relationship
• When only one instance of an entity is associated with the relationship,
then it is known as one to one relationship.
Relationship - One-to-many relationship
• When only one instance of the entity on the left, and more than one
instance of an entity on the right associates with the relationship then
this is known as a one-to-many relationship.
Relationship - Many-to-one relationship
• When more than one instance of the entity on the left, and only one
instance of an entity on the right associates with the relationship then
it is known as a many-to-one relationship.
Relationship - Many-to-many relationship
• When more than one instance of the entity on the left, and more than
one instance of an entity on the right associates with the relationship
then it is known as a many-to-many relationship.
Notation of ER diagram
Mapping Constraints
• A mapping constraint is a data constraint that expresses the number
of entities to which another entity can be related via a relationship set.
• It is most useful in describing the relationship sets that involve more
than two entity sets.
• For binary relationship set R on an entity set A and B, there are four
possible mapping cardinalities. These are as follows :
• One to one (1:1)
• One to many (1:M)
• Many to one (M:1)
• Many to many (M:M)
Mapping Constraints - One-to-one
• In one-to-one mapping, an entity in E1 is associated with at most one
entity in E2, and an entity in E2 is associated with at most one entity in
E1.
Mapping Constraints - One-to-many
• In one-to-many mapping, an entity in E1 is associated with any
number of entities in E2, and an entity in E2 is associated with at most
one entity in E1.
Mapping Constraints - Many-to-one
• In one-to-many mapping, an entity in E1 is associated with at most
one entity in E2, and an entity in E2 is associated with any number of
entities in E1.
Mapping Constraints - Many-to-many
• In many-to-many mapping, an entity in E1 is associated with any
number of entities in E2, and an entity in E2 is associated with any
number of entities in E1.
Module 3
Postgree Client
Connecting to PostgreSQL databases
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.
Using psql
• First, launch the psql program and connect to the
PostgreSQL Database Server using the postgres
user:
Using psql (continued)
• Second, enter all the information such as Server,
Database, Port, Username, and Password.
Using psql (continued)
• Third, interact with the PostgreSQL Database
Server by issuing an SQL statement.
• SELECT version();
Using psql from Command Prompt
• psql -h <hostname> -p <port> -U <username> -
d <database>
Using psql from Command Prompt (continued)
Some of Psql commands
Command Description Additional Information
psql -d database -U user -W Connects to a database under a specific user -d: used to state the database name
-U:used to state the database user
psql -h host -d database -U user -W Connect to a database that resides on another host -h: used to state the host
-d: used to state the database name
-U:used to state the database user
psql -U user -h host “dbname=db
Use SSL mode for the connection -h: used to state the host
sslmode=require”
-U:used to state the database user
\c dbname Switch connection to a new database
\l List available databases
\dt List available tables
Describe a table such as a column, type, modifiers of columns,
\d table_name
etc.
\dn List all schemes of the currently connected database
\df List available functions in the current database
\dv List available views in the current database
\du List all users and their assign roles
SELECT version(); Retrieve the current version of PostgreSQL server
\g Execute the last command again
\s Display command history
\s filename Save the command history to a file
\i filename Execute psql commands from a file
\? Know all available psql commands
Eg:to get detailed information on ALTER TABLE statement
\h Get help
use the \h ALTER TABLE
\e Edit command in your own editor
\a Switch from aligned to non-aligned column output
\H Switch the output to HTML format
\q Exit psql shell
• The full list of Psql commands is available
• [Link]
Using pgAdmin
• First, launch the pgAdmin application.
Using pgAdmin (continued)
• The pgAdmin application will launch
• Input master password
Using pgAdmin (continued)
• Second, Double click the Servers node
Module 4
Building Database
Database
PostgreSQL use databases and tables to
structure and organize their data.
Terms quickly
• Databases
• separate different sets of structures and data from one
another
• Schema
• a namespace within a database that contains tables,
indexes, views, and other items.
• Tables
• define the data structure and store the actual data
values within databases
Managing Databases
• In this section, you will learn how to manage
databases in PostgreSQL including creating
databases, modifying existing database features,
and deleting databases.
• Create Database – create a new database using CREATE
DATABASE statement.
• Alter Database – modify the features of an existing
database using the ALTER DATABASE statement.
• Rename Database – change the name of the database to
a new one.
Managing Databases (continued)
• Drop Database – removes a database permanently using
the DROP DATABASE statement.
• Copy a Database – copy a database within a database
server or from a server to another.
• Get Database Object Sizes – introduce you to various
handy functions to get the size of a database, a table,
and indexes.
PostgreSQL CREATE DATABASE statement
CREATE DATABASE database_name
WITH
[OWNER = role_name]
[TEMPLATE = template]
[ENCODING = encoding]
[LC_COLLATE = collate]
[LC_CTYPE = ctype]
[TABLESPACE = tablespace_name]
[ALLOW_CONNECTIONS = true | false]
[CONNECTION LIMIT = max_concurrent_connection]
[IS_TEMPLATE = true | false ]
PostgreSQL CREATE DATABASE examples
• Create a database with default parameters
CREATE DATABASE MyDb;
• Create a database with some parameters
CREATE DATABASE TrainingDb
WITH
ENCODING = 'UTF8'
OWNER = postgres
CONNECTION LIMIT = 100;
PostgreSQL ALTER DATABASE statement
• The ALTER DATABASE statement allows you to
carry the following action on the database:
• Change the attributes of the database
• Rename the database
• Change the owner of the database
• Change the default tablespace of a database
• Change the session default for a run-time configuration
variable for a database
Changing attributes of a database
• To change the attributes of a database, you use
the following form of the ALTER TABLE statement:
ALTER DATABASE name WITH option;
• The option can be:
• IS_TEMPLATE
• CONNECTION LIMIT
• ALLOW_CONNECTIONS
Rename the database
• The following ALTER DATABASE RENAME TO
statement renames a database:
ALTER DATABASE database_name
RENAME TO new_name;
• Only superusers and database owners with
CREATEDB privilege can rename the database.
Change the owner of the database
• The following ALTER DATABASE statement
changes the owner of a database to the new one:
ALTER DATABASE database_name
OWNER TO new_owner | current_user |
session_user;
• The following users can change the onwer of the
database:
• The database owner with CREATEDB privilege and is a
direct or indirect member of the new owning role.
• The superusers
Change the default tablespace of a database
• The following statement changes the default
tablespace of the database:
ALTER DATABASE database_name
SET TABLESPACE new_tablespace;
• The statement physically moves tables and indexes
from the legacy tablespace to the new one.
• To set the new tablespace, the tablespace needs to be
empty and there is connection to the database.
• Superusers and database owner can can change the
default tablespace of the database
Change session defaults for run-time configuration variables
• The following statement changes session defaults
for run-time configuration variables:
ALTER DATABASE database_name
SET configuration_parameter = value;
• Only superusers or database owners can change
the session default for a run-time configuration
for the database.
PostgreSQL ALTER DATABASE examples
• [Link]
PostgreSQL DROP DATABASE statement
• The syntax of the DROP DATABASE statement:
DROP DATABASE [IF EXISTS] database_name;
To delete a database:
• Specify the name of the database that you want to
delete after the DROP DATABASE clause.
• Use IF EXISTS to prevent an error from removing a
non-existent database. PostgreSQL will issue a
notice instead.
• Only superusers and the database owner can
execute the DROP DATABASE statement.
Drop a database that has active connections
• First, find the activities associated with the
database by querying the pg_stat_activity view:
SELECT * FROM pg_stat_activity
WHERE datname = '<database_name>’;
• Second, terminate the active connections by
issuing the following query:
SELECTpg_terminate_backend (pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname =
'<database_name>';
Drop a database that has active connections (continued)
• Third, execute the DROP DATABASE statement:
DROP DATABASE <database_name>;
PostgreSQL DROP DATABASE examples
• [Link]
Module 5
Postgre Table
PostgreSQL CREATE TABLE
Syntax of the CREATE TABLE statement
CREATE TABLE [IF NOT EXISTS] table_name (
column1 datatype(length) column_contraint,
column2 datatype(length) column_contraint,
column3 datatype(length) column_contraint,
table_constraints
);
Constraints
• Column constraints:
• NOT NULL – ensures that values in a column cannot be NULL.
• UNIQUE – ensures the values in a column unique across the rows
within the same table.
• PRIMARY KEY – a primary key column uniquely identify rows in a
table. A table can have one and only one primary key. The primary
key constraint allows you to define the primary key of a table.
• CHECK – a CHECK constraint ensures the data must satisfy a
boolean expression.
• FOREIGN KEY – ensures values in a column or a group of columns
from a table exists in a column or group of columns in another
table. Unlike the primary key, a table can have many foreign keys.
• Table constraints are similar to column constraints except
that they are applied to more than one column.
PostgreSQL CREATE TABLE examples
• [Link]
PostgreSQL ALTER TABLE
The ALTER TABLE statement:
• ALTER TABLE table_name action;
PostgreSQL provides you with many actions:
• Add a column
• Drop a column
• Change the data type of a column
• Rename a column
• Set a default value for the column.
• Add a constraint to a column.
• Rename a table
PostgreSQL ALTER TABLE (continued)
• ALTER TABLE ADD COLUMN statement:
ALTER TABLE table_name
ADD COLUMN column_name datatype column_constraint;
• ALTER TABLE DROP COLUMN statement:
ALTER TABLE table_name
DROP COLUMN column_name;
• ALTER TABLE RENAME COLUMN TO statement:
ALTER TABLE table_name
RENAME COLUMN column_name
TO new_column_name;
PostgreSQL ALTER TABLE (continued)
• ALTER TABLE ALTER COLUMN SET DEFAULT or DROP
DEFAULT:
ALTER TABLE table_name
ALTER COLUMN column_name
[SET DEFAULT value | DROP DEFAULT];
• ALTER TABLE ALTER COLUMN statement:
ALTER TABLE table_name
ALTER COLUMN column_name
[SET NOT NULL| DROP NOT NULL];
• ALTER TABLE ADD CHECK statement:
ALTER TABLE table_name
ADD CHECK expression;
PostgreSQL ALTER TABLE (continued)
• ALTER TABLE ADD CONSTRAINT statement:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_definition;
• ALTER TABLE RENAME TO statement:
ALTER TABLE table_name
RENAME TO new_table_name;
PostgreSQL ALTER TABLE examples
• [Link]
PostgreSQL DROP TABLE
The DROP TABLE statement as follows:
DROP TABLE [IF EXISTS]
table_name_1,
table_name_2,
...
[CASCADE | RESTRICT];
• The IF EXISTS option to remove the table only if it exists.
• The CASCADE option allows you to remove the table and its
dependent objects.
• The RESTRICT option rejects the removal if there is any object
depends on the table.
• The RESTRICT option is the default.
PostgreSQL DROP TABLE examples
• [Link]