PostgreSQL Guide for Oracle DBAs
PostgreSQL Guide for Oracle DBAs
FOR
ORACLE DBAS
-Ritesh Das
PostgreSQL for Oracle DBAS
Table of Contents
-Ritesh Das
• Listener in Postgres?
• Memory Comparison
Ritesh Das
Contents Of $PGDATA & Config
05 Instance Management 06 Files
-Ritesh Das
07 Structures 08 System Catalog
• Global Objects
• Tablespaces
• System Catalog
• Temporary Tablespace • Corelation of Dictionary Views
• Datafiles • pg_catalog vs information_schema
• TOAST (The Oversized-Attribute Storage • Functions
Technique)
Ritesh Das
09 Concurrency Control 10 VACUUM
11 Extensions 12 PGADMIN
• Top Extensions
• Installation and Managing Extensions
-Ritesh Das
13 User Management 14 Backup & Recovery
• Understanding LSN, WAL Segments & WAL Logs
• Enable Archive Mode
• Database Crash Recovery
• Timelines (Incarnations)
• Logical Backups
• Physical Backup (pg_basebackup)
• Point in time Recovery
Ritesh Das
15 Patching & Upgrades 16 Performance Tuning
-Ritesh Das
pg_profile
17 High Availability
18 Database Maintenance
1. Comparison of HA options between Oracle &
Postgres • Regular Administration & Maintenance Activities
2. Understanding Streaming Replication • Managing Bloat
3. Replication Slots • Reindex
4. Replication Manager • Debugging
5. PGBouncer
6. PGPool –II
7. Demo
Ritesh Das
PostgreSQL for Oracle DBAS
01
High Level
-Ritesh Das
Compairson
Oracle/Postgresql
Ritesh Das
High Level Comparison
-Ritesh Das
Large Object Storage SecureFiles TOAST (The Oversized-Attribute Storage Technique)
Automatic Storage ASM (Automatic Storage
No direct equivalent; managed by filesystem or LVM
Management Management)
Range, Interval, Hash, List,
Partitioning Range, Hash, List, Composite
Composite, Reference
Replication Data Guard, GoldenGate Streaming Replication, Logical Replication
Oracle RAC (Real Application
Cluster Management No direct equivalent
Clusters)
Flashback Database, Flashback No direct equivalent, use Point-in-Time Recovery
Flashback Technology
Table, Flashback Query (PITR)Ritesh Das
Feature Oracle PostgreSQL
-Ritesh Das
MVCC (Multiversion Multi-Version Concurrency Control (MVCC) with
Control (MVCC) with Undo
Concurrency Control) Transaction ID
Segments
Oracle Connection Manager,
Connection Pooling PgBouncer, Pgpool-II
DRCP
Remote Databases Database Links Foreign Data Wrappers (FDWs)
Not as advanced as Oracle, use of pg_hint_plan,
SQL Profiles, SQL Baselines, SQL
pg_stat_statements, pg_profile (all of these are
Performance Tuning Tuning Advisor, Hints, AWR,
through extensions), Pgbadger (tool to analyze log
ADDM
files)
Auditing Oracle Audit Vault Ritesh Das
PostgreSQL Audit (pgAudit) extension
Terminology
Table/Index Relation
Row Tuple
-Ritesh Das
Column Attribute
Ritesh Das
PostgreSQL for Oracle DBAS
02
Architecture
-Ritesh Das
1. Database Cluster & Instance
2. Process Comparison
3. Functions of Postmaster
4. Listener in Postgres?
5. Memory Comparison
Ritesh Das
Database Cluster & Instance
Ritesh Das
Database Cluster & Instance
• Instance: A group of backend and auxiliary processes that communicate using a common shared memory area.
• One postmaster process manages the instance; one instance manages exactly one database cluster with all its databases.
-Ritesh Das
• More than one postgres instance can run on a server at one time, so long as they use different data areas and different
communication ports.
Ritesh Das
[postgres@vagrantpgsql ~]$ ps -ef|grep postgres
postgres 657 1 0 Apr30 ? 00:00:00 /usr/pgsql-15/bin/postmaster -D /var/lib/pgsql/15/data/
postgres 688 657 0 Apr30 ? 00:00:00 postgres: logger
-Ritesh Das
postgres 2909 2908 0 02:52 pts/2 00:00:00 -bash
postgres 2941 2909 0 02:53 pts/2 00:00:00 ps -ef
postgres 2942 2909 0 02:53 pts/2 00:00:00 grep --color=auto postgres
[postgres@vagrantpgsql ~]$ pstree -p 657
postmaster(657)─┬─postmaster(688)
├─postmaster(692)
├─postmaster(693)
├─postmaster(923)
├─postmaster(925)
└─postmaster(926)
[postgres@vagrantpgsql ~]$ pstree -p 2812
postgres(2812)─┬─postgres(2813)
├─postgres(2814)
├─postgres(2815)
Ritesh Das
├─postgres(2817)
├─postgres(2818)
└─postgres(2819)
Process Comparison
-Ritesh Das
Oracle
Ritesh Das
Functions of Postmaster
Loads configuration files, initializes shared memory segments, and prepares the server
Server Initialization
for operation.
-Ritesh Das
Process Lifecycle Starts all PostgreSQL server processes, including background processes for database
Manager management and client connections.
Background Process Continuously monitors the health of all background server processes (such as background
Monitoring writer, checkpoint, and autovacuum processes.
Handles server shutdown gracefully, ensuring proper termination of all server processes
Handling Shutdown and data integrity. This might involve flushing buffers, writing commits to disk, and
closing connections.
Ensures data consistency after an instance crash by applying Write-Ahead Log (WAL)
Crash Recovery
records.
Ritesh Das
Background Processes and its functions
-Ritesh Das
-- Access data.
Cleans up dead rows and reclaims space. It also Gathers statistics about
Autovacuum Launcher
database objects (tables, indexes)
Background Writer Writes data changes from memory buffers to data files on disk.
Periodically creates a consistent snapshot of the database for faster recovery in
Checkpoint
case of crashes.
WAL Writer Writes changes (Write-Ahead Logs) to the Write-Ahead Log (WAL) files.
Log Collector Writes error log messages to logfiles
Archiver Copies WAL Files to a separate file system for Point in time Recovery.
Ritesh Das
Listener in Postgres?
-Ritesh Das
[postgres@vagrantpgsql ~]$ psql
psql (15.6)
Type "help" for help.
postgres=#
[postgres@vagrantpgsql ~]$ pstree -p 651
postmaster(651)─┬─postmaster(684)
├─postmaster(688)
├─postmaster(689) Background
├─postmaster(938) processes
├─postmaster(939)
├─postmaster(940)
└─postmaster(2067)
[postgres@vagrantpgsql ~]$ Ritesh Das
Backend processes
Memory Comparison
• Parameter: wal_buffers
Redolog Buffer WAL Buffer • Stores transactional changes before they are written to disk,
providing durability and allowing for crash recovery.
-Ritesh Das
sort_area_size work_mem • Parameter: work_mem
• For each backend process for sorting.
maintenance_work_me
m • Postgres writes to disk(temp files) if memory is not sufficient.
Ritesh Das
Shared Pool Shared Pool from temporary tables.
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Installation
03
PostgreSQL for Oracle DBAS
04 PSQL>
Working with
Postgres=#
-Ritesh Das
PSQL
1. Playing around with psql
2. .pgpass
3. .psqlrc
Ritesh Das
.pgpass
postgres=>
-Ritesh Das
Format:
[Link]:mydatabase:myuser:mypassword
[Link]:5432:postgres:postgres:pg_password
chmod 0600 ~/.pgpass
postgres=>
Ritesh Das
.psqlrc
-Ritesh Das
Format Result
\set sel 'SELECT * FROM ' Define shortcuts for frequently used commands or
queries.
\timing Shows the execution time of queries
Add a + to any command below to get extended info • By default, it copies the standard system database
Shortcut Description named template1.
-Ritesh Das
\l List databases in the cluster • If you add objects to template1, these objects will
\d list tables, views, and sequences be copied into subsequently created user databases.
\d [name] describe table, view, sequence, or
• There is also a template0 which is exactly same as
index
\db List of tablespaces the initial contents of template1.
-Ritesh Das
Management
1. Startup Modes
2. Shutdown Modes
3. Reload
Ritesh Das
Startup Modes
-Ritesh Das
No Mount No
Intermediary
modes
Mount
Open Open
Ritesh Das
Shutdown Modes
Comparable
-Ritesh Das
pg_ctl -D $PGDATA stop -mf
Immediate Fast (Default)
Transactional
Ritesh Das
Reload
-Ritesh Das
Or
● SELECT pg_reload_conf();
Ritesh Das
06
-Ritesh Das
1. Folder Structure of PGDATA
2. Control File
3. Configuration Files
4. Important Parameters – [Link]
5. Context of Parameter to determine Static/Dynamic Parameters
6. Using tools for setting recommended parameters.
7. pg_hba.conf
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
pg_control Control File
-Ritesh Das
● It is essential during database
recovery.
● It is a binary file and is present in
$PGDATA/global. To see the
contents, we use a pg_controldata
executable.
Ritesh Das
[Link]
-Ritesh Das
● When the PostgreSQL server starts up, it first reads the main configuration file
called “[Link]” Parameters from “[Link]” overwrites ones in
[Link]
Ritesh Das
Understanding Parameter Context
-Ritesh Das
Dynamic sighup Parameters that require a reload to apply Changes can be applied with a pg_ctl reload
command.
The backend parameters can be changed/set
eg: post_auth_delay
Dynamic backend while making a new connection to Postgres, and
Changes apply to new sessions.
cannot be changed once the session is started.
log_min_duration_statement.
Dynamic superuser Parameters that can be changed by superusers Changes apply immediately and can be modified
by superusers to aid in performance diagnostics.
search_path
Changes take effect immediately for the current
Dynamic user Parameters that can be changed by any user
Ritesh Das
session and affect how SQL queries resolve
object names.
Altering Parameters at multiple levels
● Cluster level :
ALTER SYSTEM SET max_parallel_workers TO 4;
● Database level :
-Ritesh Das
ALTER DATABASE database_name SET max_parallel_workers TO 4;
● User level :
ALTER ROLE user_name SET max_parallel_workers TO 2;
● Transaction level:
BEGIN;
SET LOCAL max_parallel_workers TO 4;
Ritesh Das
Some important parameters
-Ritesh Das
Determines how much information is written to the write-ahead log for crash recovery
wal_level
and replication.
Specifies the maximum number of simultaneous connections from standby servers for
max_wal_senders
replication.
Values: none, ddl, mod (dml), all. Log Statements in Postgresql Logs –Useful for tracing,
log_statement
troubleshooting.
Enables or disables archiving of WAL (Write Ahead Log) files for backup and point-in-time
archive_mode
recovery.
archive_command Specifies the command to use to archive a WAL file when archive_mode is enabled.
Ritesh Das
PostgreSQL for Oracle DBAS
log_line_prefix
● The log_line_prefix parameter is used to specify the format of log line prefixes in the PostgreSQL server log.
● By Default it is “%m [%p]” (Time Stamp and Process ID)
-Ritesh Das
alter system set log_line_prefix = '%t [%p]: [%l-1] db=%d,user=%u,app=%a,client=%h’;
%t – timestamp, %p – process id, %l – log line number, %d – dbname, %u – username,
%d – application name, %h – hostname/ip
-Ritesh Das
Tool Description
Web-based tool for generating optimized [Link]
pgtune PostgreSQL settings based on hardware and a/
workload.
An open-source web-based tool provided [Link]
pg_configurator by CyberTec for generating optimized [Link]/
PostgreSQL configurations.
[Link] analyses your [Link]
postgresqltuner.
PostgreSQL instance and produces a report, ostgresqltuner
pl
giving hints. It is inspired by [Link]
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
pg_hba.conf
-Ritesh Das
Complete list of Methods:
TYPE DATABASE USER ADDRESS METHOD
local db1 user1 CIDR trust "trust", "reject", "md5",
"password", "scram-sha-256",
Host db1,db2 etc user1,user2 reject "gss", "sspi", "ident", "peer",
"pam", "ldap", "radius“, "cert".
hostssl @[Link] @[Link] md5
hostnossl all all password Note that "password" sends
passwords in clear text.
hostgssenc scram-sha-256 "md5" or "scram-sha-256" are
hostnogssenc gss Ritesh Das
preferred since they send
encrypted passwords.
PostgreSQL for Oracle DBAS
Authentication Methods
Authentication
Description
Method
trust Allows any user to connect without authentication. Use with caution; it bypasses security.
reject Rejects all connection attempts, regardless of user or IP address.
-Ritesh Das
md5 Requires a password for authentication. Passwords are hashed using MD5.
password Requires a password for authentication. Encrypted passwords are sent over the network.
scram-sha-256 Securely hashes passwords using the SCRAM-SHA-256 algorithm.
gss Uses GSSAPI (Kerberos) authentication.
sspi Windows-only authentication using SSPI (Security Support Provider Interface).
cert Requires SSL certificates for authentication.
peer Authenticates the system user based on the client’s operating system username.
ldap Uses LDAP (Lightweight Directory Access Protocol) for authentication.
Ritesh Das
Example
-Ritesh Das
local all senior-dba Trust
Session2 -[Link]
Host erp apps [Link]/24 md5
apps@erp
Ritesh Das
Examples
-Ritesh Das
host erpdb apps [Link]/24 md5 using MD5.
Allows connection from localhost to all users and all
local all all trust databases without any password.
Allows host range "[Link]/24" to connect with apps,
erpdb, apps, catuser user to databases erpdb and catalog databases,
host catalog catuser [Link]/24 password using Password based authentication.
Ritesh Das
PostgreSQL for Oracle DBAS
07
Logical & Physical
-Ritesh Das
Structures
1. Global Objects
2. Tablespaces
3. Temporary Tablespace
4. Datafiles
5. TOAST (The Oversized-Attribute Storage Technique)
Ritesh Das
Global Objects
-Ritesh Das
Global Object Description
Roles are cluster-wide entities, meaning they exist and can be used across all
User/Roles
databases within a PostgreSQL cluster.
Storage locations where database objects are stored, providing flexibility in
Tablespaces
managing storage locations.
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
High level structure
Database Database
1 2
-Ritesh Das
Schema 1 Schema 2 Schema 1 Schema 2
Ritesh Das
Tablespaces
-Ritesh Das
● By placing heavily used objects (e.g., indexes) on fast, highly available disks and less
critical data (e.g., archived data) on slower disks, you can optimize performance.
Ritesh Das
Tablespaces
-Ritesh Das
archive_date TIMESTAMP
) TABLESPACE arch_tbs;
Ritesh Das
ALTER TABLE employees
SET TABLESPACE data_tbs;
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Tablespaces
Temporary Tablespace
● Parameter: temp_tablespaces
○ Multiple tablespaces can be defined in this parameter.
-Ritesh Das
○ If no temp tablespace is defined then postgres uses default tablespace.
● Usage:
○ During Large Sorts
○ Hash Joins
○ Temporary Tables
Ritesh Das
Co-relation between work_mem and Temporary
-Ritesh Das
work_mem Temporary tablespace
In Memory, Fast
Disk, Slow
Ritesh Das
Datafiles
● When a table or a index exceeds 1GB, it is divided into gigabyte-sized segments. The first segment's file name is
-Ritesh Das
the same as the filenode; subsequent segments are named filenode.1, filenode.2, etc.
● Actually, 1 GB is just the default segment size. The segment size can be adjusted using the configuration option --
with-segsize when building PostgreSQL.
Ritesh Das
-rw-------. 1 postgres postgres 1073741824 Feb 28 11:45 16454.5
-rw-------. 1 postgres postgres 601964544 Feb 28 11:45 16454.6
-rw-------. 1 postgres postgres 0 Feb 28 11:30 16457
-rw-------. 1 postgres postgres 8192 Feb 28 11:30 16458
PostgreSQL for Oracle DBAS
TOAST
TOAST
(The Oversized-
Attribute Storage
-Ritesh Das
Technique)
Ritesh Das
Block (8kb) Block
Block
-Ritesh Das
Toast Table
Oversized ROW
-Ritesh Das
alter table tablename alter column columnname set storage external;
Ritesh Das
PostgreSQL for Oracle DBAS
08
System Catalog
-Ritesh Das
1. System Catalog
2. Corelation of Dictionary Views
3. pg_catalog vs information_schema
4. Functions
Ritesh Das
System Catalog
-Ritesh Das
and indexes.
● It is included in the search path by default, meaning its tables and views can be
accessed without specifying the schema name.
Complete list of catalogs: [Link]
Ritesh Das
Corelation of Dictionary views
-Ritesh Das
v$tablespace pg_tablespace Information about tablespaces
pg_tablespace and Information about data files (PostgreSQL uses
v$datafile
pg_class tablespaces and file storage differently)
v$lock pg_locks Information about locks held in the database
v$sysstat pg_stat_database System statistics
Lists redolog/wal files. Pg_wal directory also has
v$logfile pg_ls_waldir()
metadata
Ritesh Das
Corelation of Dictionary Views
-Ritesh Das
dba_constraints pg_constraint table_constraints
dba_cons_columns pg_constraint and pg_attribute key_column_usage
dba_users pg_authid users (not directly comparable)
dba_sequences pg_sequences sequences
dba_synonyms Synononyms not supported in PG Synononyms not supported in PG
dba_triggers pg_trigger triggers
dba_objects pg_class tables, views, sequences, etc.
dba_roles pg_roles applicable_roles
Ritesh Das
pg_catalog vs information_schema
-Ritesh Das
information about PostgreSQL-specific features; to inquire about those you need to query the system
catalogs or other PostgreSQL-specific views.”
Ritesh Das
Functions
-Ritesh Das
SELECT pg_get_indexdef returns the definition of an
pg_get_indexdef
pg_get_indexdef('my_index'::regclass); index.
SELECT
pg_create_restore_poi pg_create_restore_point creates a named
pg_create_restore_point('my_restore_point
nt restore point.
');
pg_current_wal_lsn returns the current write-
pg_current_wal_lsn SELECT pg_current_wal_lsn(); ahead log (WAL) location as an LSN (Log
Sequence Number).
SELECT pg_backup_start initiates a base backup operation
pg_backup_start
pg_backup_start('my_backup_label'); with the specified label.
pg_switch_wal SELECT pg_switch_wal();
segment. Ritesh Das
pg_switch_wal forces a switch to a new WAL
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Concurrency
Control
09
Multi-Version Concurrency Control
Table
Oracle
Until
update Session1 commit
New row
update
New row v2
Session1
Old row v1
-Ritesh Das
Undo Tablespace
Ritesh Das
MVCC
-Ritesh Das
User2 When a new session, ie user 4 queries
EMP Table
the row, then it find the updated data
Empno Ename Role Salary ie (v2)
2132 Mike System Analyst 3000 Row (v1) is now marked as dead tuple,
118 Scott Manager 7500 which will be cleaned up by the vaccum process
User2
update
User3 Ritesh Das
PostgreSQL for Oracle DBAS
10
Vacuum
-Ritesh Das
1. VACUUM
2. AUTOVACUUM
3. Transaction ID Wrap Around
4. Autovacuum parameters
5. Understanding these parameters
Ritesh Das
VACUUM
Regular VACUUM:
○ Reclaims space and makes it available for re-use.
○ Does not obtain exclusive lock.
○ Does not return space back to OS.
-Ritesh Das
VACUUM FULL:
○ Rewrites the entire table contents into a new disk file, allowing unused space to be returned to the
OS.
○ It is slower and requires an ACCESS EXCLUSIVE lock on the table.
Syntax:
VACUUM [ (option [, ...]) ] [table_and_columns [, ...]]
Options:
FULL: Selects “full” vacuum (reclaims more space but takes longer).
VERBOSE: Provides detailed output during the process.
ANALYZE: Performs both VACUUM and ANALYZE for each selected table.
Ritesh Das
AUTOVACUUM
-Ritesh Das
Tasks of Autovacuum:
○ Clean up Dead Tuples
o Running Analyze to keep table statistics up-to-date.
o Prevents Transaction Wrap Around.
o Updates visibility map
Ritesh Das
Transaction Wrap Around
● Autovacuum
-Ritesh Das
○ It recycles XIDs by marking XIDs as Frozen.
○ It freezes XIDs which are older than the frozen XID threshold.
○ Frozen XIDs are safe to reuse.
○ Oldest XIDs are recycled first.
Ritesh Das
Autovacuum parameters
-Ritesh Das
Specifies the minimum number of updated or inserted tuples needed to trigger an
autovacuum_analyze_threshold 50
ANALYZE operation.
Specifies a fraction of the table size to trigger a VACUUM operation based on the
autovacuum_vacuum_scale_factor 0.2
number of dead tuples.
Specifies a fraction of the table size to trigger an ANALYZE operation based on the
autovacuum_analyze_scale_factor 0.1
number of tuples.
Sets the maximum age in transactions before a table row is considered for anti-
autovacuum_freeze_max_age 200 million
wraparound vacuuming.
autovacuum_multixact_freeze_max Sets the maximum age in multixact transactions before a row is considered for anti-
400 million
_age wraparound vacuuming.
Specifies the delay between VACUUM operations to avoid impacting other database 20
autovacuum_vacuum_cost_delay
autovacuum_vacuum_cost_limit
activity.
Specifies the maximum time that VACUUM operations can consume.
Ritesh Das milliseconds
-1 (no limit)
autovacuum_max_workers
Autovacuum_naptime
(60 seconds)
Cleanup up
the tables
Yes
No?
Go back to sleep
Work to
be done?
autovacuum_vacuum_scale_factor autovacuum_vacuum_threshold
% of rows changed (20%) # of rows changed (50)
What qualifies as
work?
autovacuum_analyze_scale_factor autovacuum_analyze_threshold
% of rows changed (10%) # of rows changed (50)
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Understanding these parameters
-Ritesh Das
1. autovacuum_vacuum_scale_factor (0.2 default) – if 20% of data is changed in a table. If a table
has just 1 row, updating 1 row would cause 100% change in rows. That is why we have the next
parameter.
2. autovacuum_vacuum_threshold (50 default) – There should be atleast 50 rows effected.
-Ritesh Das
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Extensions
11
Extensions
-Ritesh Das
○ contrib Module: For stable, officially supported extensions included with PostgreSQL.
○ PGXN: For a wide range of easily installable extensions.
○ Git Repositories: For the latest and custom development versions.
Ritesh Das
TOP Extensions for DBAs
pg_repack Reorganizes tables and indexes without locks. PGXN, Git ([Link]
Schedules PostgreSQL commands directly from the
pg_cron Git ([Link]
database.
pg_partman Manages time-based and serial-based table partition sets. PGXN, Git ([Link]
-Ritesh Das
pgaudit Provides detailed session and object audit logging. PGXN, Git ([Link]
pg_hint_plan Enables hinting the planner on how to execute queries. PGXN, Git ([Link]
● Source PGXN
○ pgxn install <extension name> [Ensure pgxn is installed]
● Source Contrib
○ Ensure contrib module is installed at OS level.
-Ritesh Das
○ sudo yum install -y postgresql15-contrib.x86_64
● Source GIT
○ Follow installation instructions on the git page.
Ritesh Das
3. Install extension at DB level
-Ritesh Das
Or \dx
Ritesh Das
Managing Extensions
● Removing Extensions
-Ritesh Das
DROP EXTENSION IF EXISTS pg_stat_statements;
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
PGADMIN
12
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
PGADMIN DEMO
-Ritesh Das
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Management
User
13
User and Schema
-Ritesh Das
Cluster
Users Tablespaces
Databases
Database 1 Database 2
Ritesh Das
Tables Table Table Table Table Table Table Table
Users & Roles
-Ritesh Das
create user user1 password 'user1'; create role user1 login password 'user1';
Database
● For simplicity we will create users with create user command.
● We need to give explicit privleges to every entity to the user.
○ CREATE USER apps_erp WITH PASSWORD 'apps_erp';
○ GRANT ALL ON DATABASE erpdb2 TO apps_erp ;
○ GRANT ALL ON SCHEMA app_schema TO apps_erp; Schema
Tables
Ritesh Das
PostgreSQL for Oracle DBAS
Privileges to role and role to User
-Ritesh Das
Privileges directly to User
Ritesh Das
Attributes
-Ritesh Das
CREATEDB
databases. DATABASE higher system level).
WITH PASSWORD
Allows the role to create, alter, and CREATE USER, Allows the user to create and manage other
'test1’ SUPERUSER; CREATEROLE
drop other roles. ALTER USER database users.
Allows the role to inherit the privileges Users can be granted multiple roles and inherit
INHERIT Role Inheritance
ALTER user test1 of roles it is a member of. the privileges of those roles.
SUPERUSER; LOGIN
Allows the role to log in to the CREATE
Allows the user to connect to the database.
database. SESSION
Allows the role to initiate streaming
SYSDG (Data Includes privileges for managing and initiating
REPLICATION replication and manage replication
Guard) data replication and standby databases.
slots.
BYPASSRLS
Allows the role to bypass row-level
security policies.
Bypass
VPD/FGAC
Ritesh Das
Allows the user to bypass Virtual Private
Database (VPD) policies or Fine-Grained Access
Control (FGAC).
Pre-Defined Role Allowed Access
Read all data (tables, views, sequences), as if having SELECT rights on those objects, and USAGE rights on all
schemas, even without having it explicitly. This role does not have the role attribute BYPASSRLS set. If RLS is being
-Ritesh Das
pg_database_owner None. Membership consists, implicitly, of the current database owner.
pg_signal_backend Signal another backend to cancel a query or terminate its session.
Allow reading files from any location the database can access on the server with COPY and other file-access
pg_read_server_files functions.
Allow writing to files in any location the database can access on the server with COPY and other file-access
pg_write_server_files functions.
pg_execute_server_pro Allow executing programs on the database server as the user the database runs as with COPY and other functions
gram which allow executing a server-side program.
pg_checkpoint Allow executing the CHECKPOINT command.
pg_use_reserved_conn
ections Allow use of connection slots reserved via reserved_connections.
pg_create_subscription Allow users with CREATE permission on the database to issue CREATE SUBSCRIPTION. Ritesh Das
[Link]
PostgreSQL for Oracle DBAS
ADMIN-ROLE=RW-Role+
Group Manager
All Privileges
Role Inheritance
Inherits Inherits
RW-Role=RO-Role+
Line Manager
-Ritesh Das
Insert, Update
Inherits Inherits
Ritesh Das
Privileges for Object Types
Table SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, ALL PRIVILEGES
-Ritesh Das
Sequence USAGE, SELECT, UPDATE, ALL PRIVILEGES
Schema CREATE, USAGE, ALL PRIVILEGES
Database CREATE, CONNECT, TEMP, ALL PRIVILEGES
Function EXECUTE, ALL PRIVILEGES
Procedure EXECUTE, ALL PRIVILEGES
Type USAGE, ALL PRIVILEGES
Domain USAGE, ALL PRIVILEGES
Ritesh Das
Abbreviations for Privileges
-Ritesh Das
CREATE C DATABASE, SCHEMA, TABLESPACE
CONNECT c DATABASE
TEMPORARY T DATABASE
EXECUTE X FUNCTION, PROCEDURE
USAGE U DOMAIN, FOREIGN DATA
WRAPPER, FOREIGN
SERVER, LANGUAGE, SCHEMA, SEQUENCE, TY
PE
SET s PARAMETER
ALTER SYSTEM A PARAMETER
Ritesh Das
PostgreSQL for Oracle DBAS
14
Backup &
-Ritesh Das
Recovery
1. Understanding LSN & WAL Segments
2. Enable Archive Mode
3. Database Crash Recovery
4. Timelines (Incarnations)
5. Logical Backups
6. Physical Backup (pg_basebackup)
7. Point in time Recovery
Ritesh Das
LSN, WAL Segments
LSN
WAL Segment
-Ritesh Das
Ritesh Das
WAL Segment Name
000000020000000100000075
-Ritesh Das
LSN (1/7528DDB0)
Byte Offset(Y) |
Hexadecimal |-- Log file sequence number: 1
Timeline ID |-- Byte offset within the log file: 7528DDB0 (hex)=1,957,905,584 (decimal)
|
|-- WAL segment size: 16 MB (16,777,216 bytes)
WAL File Name: 000000020000000100000075 |
|-- WAL segment number: 1,957,905,584 / 16,777,216 ≈ 116 (or 0x75)
Log File Sequence
Number (Logical) (Physical)Segment |
|-- WAL file name: 000000020000000100000075
Ritesh Das
● Get current LSN • Get current Wal File Name:
-Ritesh Das
--------------------------+----------+------------------------
000000010000000000000014 | 16777216 | 2024-06-21 16:54:52+09
000000010000000000000015 | 16777216 | 2024-06-21 16:48:01+09
000000010000000000000016 | 16777216 | 2024-06-21 16:48:05+09
000000010000000000000017 | 16777216 | 2024-06-21 16:48:10+09
000000010000000000000018 | 16777216 | 2024-06-21 16:48:15+09
000000010000000000000019 | 16777216 | 2024-06-21 16:48:21+09
00000001000000000000001A | 16777216 | 2024-06-21 16:48:29+09
00000001000000000000001B | 16777216 | 2024-06-21 16:48:38+09
00000001000000000000001C | 16777216 | 2024-06-21 16:48:49+09 Ritesh Das
Enabling Archive Mode
-Ritesh Das
• wal_level = replica
WAL Level Description
Minimal Not enough Info for PITR, Only sufficient for Crash Recovery.
Startup Process
-Ritesh Das
CKP Perform Cleanup -removing
temporary files
Apply WAL
Logs from
Crash CKP Last CKPT
Until Crash Recovery
8pm
Ritesh Das
WAL Logs
Timeline
10 Timeline 1
2
Accidental Table drop
-Ritesh Das
Timeline 2
$PGDATA/pg_wal/[Link]
Timeline 3
1 0/1000000 no recovery target time specified
2 0/2000000 recovery target time: 2024-06-06 10:00:00
3 0/3000000 recovery target time: 2024-06-06 12:00:00
Ritesh Das
Backup & Recovery
-Ritesh Das
Barman (install separately)
-Ritesh Das
● Supports parallelism.
● Allows for compression and encryption.
Ritesh Das
pg_restore
-Ritesh Das
● Supports post-processing options such as enabling/disabling triggers.
Note: Not possible to remap schemas similar to Oracle. Workaround – Backup to SQL
file.
Ritesh Das
pg_dumpall
-Ritesh Das
● Only supports plain text format, not suitable for parallel dumps or selective
restores.
● Usually used to take backup of globals, and then backup individual databases using
pg_dump.
Ritesh Das
Backup Formats
-Ritesh Das
Parallelism Supported No No No Yes
Human-Readable Yes No No No
Restore Tool psql pg_restore pg_restore pg_restore
Supports Selective Restore Yes (Modify the file) Yes No Yes
Need a human-
Small to medium- Most use cases Very large databases
readable backup
sized databases, requiring needing maximum
Best Suited For for quick
readability, and compression and performance and
inspection
simplicity flexibility
/portability Ritesh Das
flexibility
Physical backup using pg_basebackup
-Ritesh Das
● Includes Wal Log files Plain
● Supports Compression. Directory
-Ritesh Das
host replication backup_user <client_ip_address>/32 md54
● Backup Command:
pg_basebackup -h <source_host> -U backup_user -D /path/to/backup -Ft -z -P
-h <source_host> -U backup_user -D /path/to_store_backup_files
-Ft: Specifies the tar format. -z: Compresses the backup. -P: Shows progress information.
Ritesh Das
Accidental
Backup Table delete
1. Shutdown DB
Parameter Description Scenario
Specifies what point to recover to
2. Touch $PGDATA/[Link] recovery_target
(time, transaction, etc.).
Restore to a specific point in time or event.
A name you gave to a specific Recover to a specific named event, like
recovery_target_name
3. Set appropriate recovery parameters point to restore to. "before_upgrade".
-Ritesh Das
The exact date and time to Restore to just before an unintended
recovery_target_time
4. Startup DB restore the database to. delete happened at 10 AM.
The exact transaction ID to Restore to just after transaction ID 12345
recovery_target_xid
restore to. completed.
File Name Purpose The exact log sequence number Restore to a specific point in the WAL
recovery_target_lsn
[Link] Touch to restore to. logs, like a specific operation or change.
$PGDATA/[Link] Whether to include the target Include the exact time or transaction in the
recovery_target_inclusive
Used to trigger recovery event in the recovery. recovery to verify a specific change.
mode Which timeline to use if there are
Recover to a specific timeline after a
recovery_target_timeline multiple due to previous
[Link] Used to trigger standby failover situation.
recoveries.
Ritesh Das
mode Pause recovery when reaching the target
What to do when the target is
recovery_target_action for inspection or automatically promote
reached, like pause or promote.
the standby.
PostgreSQL for Oracle DBAS
15
Patching &
-Ritesh Das
Upgrades
1. Understanding Versioning
2. Contacting Postgresql Community for help
3. Minor version Upgrade
4. Major Version Upgrade using pg_upgrade
Ritesh Das
Understanding Versioning
-Ritesh Das
● The minor version represents a patch version, which is a bug / security fix release.
● Version 16.1 (16 is the Major release and 1 is the minor release).
● Versions > 10 (Format is 10.23 – 10 major, 23 is minor)
● Versions < 10 (Format 6.4.2 – 6.4 is major, 2 is minor)
Ritesh Das
Contacting Postgresql Community for help
-Ritesh Das
● Some popular vendors are: EDB, Percona, Fujitsu, Cloud vendors such as AWS, Azure, GCP etc.
● Interesting FAQ: [Link]
A bug I'm encountering is fixed in a newer minor release of PostgreSQL, but I don't want to upgrade. Can I get a patch
for just this issue?
No. Nobody will make a custom patch for you so you can (say) extract a fix from 8.4.3 and apply it to 8.4.1 . That's
because there should never be any need to do so. If you really feel you have to do this you will need to extract the
patch from the sources yourself.
Ritesh Das
Patching to Minor Version
Stop
-Ritesh Das
Database
Yum install
new binaries
Start
Database
Ritesh Das
Upgrading to Major Version
-Ritesh Das
○ Link (Uses hard link to reference existing data files ${PGDATA})
○ Copy (Copies data ${PGDATA} from old cluster to new)
● Extensions:
○ If 3rd party extensions exist, validate its compatibility.
Ritesh Das
Comparison of Methods in pg_upgrade
-Ritesh Das
Old cluster is unusable after
Old Old cluster remains intact and
the upgrade, as files are
Cluster usable after the upgrade.
linked.
Less safe, since issues with the Safer, since the old cluster
Safety new cluster can affect the old remains unchanged and can be
cluster. used as a fallback.
Risk of data corruption if the
Data Lower risk of data corruption, as
upgrade fails, as files are
Integrity files are duplicated.
shared.
Rollback
Rollback is more complex due
to shared files.
Easier rollback to old cluster if
needed.
Ritesh Das
PostgreSQL for Oracle DBAS
Copy Method
Old PGDATA New PGDATA
/var/lib/psql/13/data /var/lib/psql/15/data
-Ritesh Das
Link Method
Ritesh Das
PostgreSQL for Oracle DBAS
Copy Method
Old PGDATA New PGDATA
/var/lib/psql/13/data /var/lib/psql/15/data
-Ritesh Das
Link Method
Ritesh Das
Upgrading to Major Version
Start
Install New Dababase
-Ritesh Das
Binaries
Post Upgrade
pg_upgrade Steps
check
Delete Old
Binaries
Stop DB
Ritesh Das
PostgreSQL for Oracle DBAS
16
Performance
Tuning
-Ritesh Das
1. Comparison of Performance Tuning Options between
Oracle & Postgres
2. Different types of Indexes
3. Partitions
4. Understanding the Explain Plan
5. Using Hints
6. Using Hints without Changing Code
7. Parallelism
8. PGBadger
9. Generarting Oracle Style AWR reports using pg_profile
Ritesh Das
Comparison of Performance Tuning Options
-Ritesh Das
AWR Report Yes Yes (PG_Profile Extension, PGBadger
tool)
Explain Plan Yes Yes (Explain, Explain Analyze) (Run time
capture using Autoexplain Extension)
Indexing Yes Yes
Statistics Yes (DBMS_STATS) Analyze command
Parallelism Yes Yes
Partition Range, Interval, Hash, List, Composite, Reference Ritesh Das
Range, Hash, List, Composite
Types of Indexes
-Ritesh Das
range. EXPLAIN ANALYZE SELECT * FROM orders WHERE
order_date BETWEEN '2023-01-01' AND '2023-01-31';
This index optimizes range queries for order_date.
-Ritesh Das
Example: Case-insensitive search by
Index expression or function. lower(customer_email) = 'customer@[Link]’;
lowercased customer email addresses.
This index optimizes searches where customer_email is compared
in lowercase.
GiST, SP-GiST, GIN - Out of Scope – These are used for complex data types such as Spatial, Geometric and full text searches. Refer to
Postgres Documentation for more information.
Ritesh Das
BRIN Index
-Ritesh Das
access patterns.
• Read heavy workloads
-Ritesh Das
Example:
CREATE TABLE orders (id serial PRIMARY KEY, order_status text NOT NULL, order_date date NOT NULL)
Divides data based on
List Partitioning PARTITION BY LIST (order_status);
predefined list of values.
CREATE TABLE orders_pending PARTITION OF orders FOR VALUES IN ('pending');
CREATE TABLE orders_completed PARTITION OF orders FOR VALUES IN ('completed');
CREATE TABLE orders_cancelled PARTITION OF orders FOR VALUES IN ('cancelled');
Use a combination of partitioning strategies (e.g., range and list).
Example:
CREATE TABLE metrics (id serial PRIMARY KEY, region text NOT NULL, event_date date NOT NULL, value
Combines two or more
Composite numeric NOT NULL) PARTITION BY RANGE (event_date) PARTITION BY LIST (region);
partitioning methods,
Partitioning CREATE TABLE metrics_2023_east PARTITION OF metrics FOR VALUES FROM ('2023-01-01') TO ('2024-01-
such as range and list.
01') FOR VALUES IN ('east');
Ritesh Das
CREATE TABLE metrics_2023_west PARTITION OF metrics FOR VALUES FROM ('2023-01-01') TO ('2024-01-
01') FOR VALUES IN ('west');
Explain vs Explain Analyze
-Ritesh Das
erpdb=# explain analyze
erpdb-# SELECT abalance FROM pgbench_accounts WHERE aid = 212843;
QUERY PLAN
-------------------------------------------------------------------------------------------------
---------------------------------------
Index Scan using pgbench_accounts_pkey on pgbench_accounts (cost=0.43..8.45 rows=1 width=4)
(actual time=5.001..5.006 rows=1 loops=1)
Index Cond: (aid = 212843)
Planning Time: 0.063 ms
Execution Time: 5.057 ms
(4 rows)
Ritesh Das
Estimated Startup Cost Estimated # Rows
-Ritesh Das
up cost rows. cost is lower, however it would be higher incase of order by.
Estimated total Total cost to retrieve all The total cost to retrieve all rows (including the start-up
cost rows, including start-up. cost) is 10.20.
Estimated
Number of rows expected The planner estimates that 100 rows will be retrieved from
number of
to be returned. the employees table where department_id = 10.
rows
Estimated
Average width in bytes of The planner estimates the average width of each row in the
average width
of rows
each returned row. result set to be 128 bytes.
Ritesh Das
PostgreSQL for Oracle DBAS
-Ritesh Das
2
3
4
21926.33/26355.61 = 83.2%
1
5
5 1690.55/26355.61 = 6.4%
6
2
3
4
4
Ritesh Das
Using Hints
-Ritesh Das
/*+ IndexScan (table_name index_name) */ Forces Index Scan
● Complete list of hints can be found in:
[Link]
Ritesh Das
testdb=# EXPLAIN SELECT *
testdb-# FROM pgbench_branches b
testdb-# JOIN pgbench_accounts a ON [Link] = [Link]
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------
Nested Loop (cost=0.57..66151.81 rows=1000000 width=461)
-> Index Scan using pgbench_accounts_pkey on pgbench_accounts a (cost=0.42..42377.43 rows=1000000 width=97)
-> Memoize (cost=0.15..0.16 rows=1 width=364)
Cache Key: [Link]
Cache Mode: logical
-> Index Scan using pgbench_branches_pkey on pgbench_branches b (cost=0.14..0.15 rows=1 width=364)
Index Cond: (bid = [Link])
(7 rows)
testdb=# /*+
testdb*# HashJoin(a b)
-Ritesh Das
testdb*# SeqScan(a)
testdb*# */
testdb-# EXPLAIN SELECT *
testdb-# FROM pgbench_branches b
testdb-# JOIN pgbench_accounts a ON [Link] = [Link]
With hint
Ritesh Das
-> Seq Scan on pgbench_branches b (cost=0.00..1.01 rows=1 width=100)
(7 rows)
The hints table
=# UPDATE hint_plan.hints
SET hints = ‘SeqScan(t1)'
WHERE id = 1;
-Ritesh Das
UPDATE 1
Ritesh Das
Parallelism
max_parallel_workers_per_gather limits the number of parallel worker processes that can be used for a single query.
-Ritesh Das
min_parallel_table_scan_size Sets the minimum size of a table for a parallel scan to be considered.
min_parallel_index_scan_size Sets the minimum size of an index for a parallel scan to be considered.
Determines whether the leader also executes subplans during parallel query
parallel_leader_participation
execution.
Sets the maximum number of parallel workers that can be used for maintenance
max_parallel_maintenance_workers
operations like VACUUM and CREATE INDEX.
parallel_setup_cost Sets the planner's estimate of the cost of launching parallel workers.
Sets the planner's estimate of the cost of passing a tuple from a parallel worker to
parallel_tuple_cost
another process. Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
PGBadger
Configuring for PGBadger
-Ritesh Das
alter system set log_temp_files = 0;
alter system set log_autovacuum_min_duration = 0;
alter system set log_error_verbosity = 'default';
alter system set log_min_duration_statement = 0;
alter system set auto_explain.log_min_duration = 0 ;
alter system set auto_explain.log_analyze = true ;
alter system set auto_explain.log_verbose = true ;
alter system set auto_explain.log_timing = true ;
alter system set auto_explain.log_nested_statements = true;
alter system set pg_stat_statements.track= 'all’;
Ritesh Das
degrades performance and captures every statement executed in the database. If this is OLTP, set it to
a value of about 5 seconds(ie 5000ms), ie it capture queries > 5 seconds per execution.
PG_Profile
-Ritesh Das
erp pg_profile
Pulls various
performance metrics
profile
via db link
-Ritesh Das
● Take Snapshots(Either manually through psql, or through cron, pgcron):
select take_sample('localhost');
Ritesh Das
PostgreSQL for Oracle DBAS
17
High Availability
-Ritesh Das
1. Comparison of HA options between Oracle & Postgres
2. Understanding Streaming Replication
3. Replication Slots
4. Replication Manager
5. PGBouncer
6. PGPool –II
7. Demo
Ritesh Das
Comparison of HA options - Oracle & Postgres
-Ritesh Das
Standby Modes:
Physical Replication:
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Understanding Streaming replication
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
Standby
Primary
Replication Slots
-Ritesh Das
• Replications slots ensure that the master
maintains all the required WAL files needed
to recover the standby database.
• Replication slots will store WAL segments
indefinitely.
Ritesh
max_slot_wal_keep_size (to limit size of WAL files retained by replication slots)Das
Replication
Physical Logical
-Ritesh Das
restart_lsn is crucial
because it indicates the
oldest WAL record needed
by the standby server.
Ritesh Das
PostgreSQL for Oracle DBAS
Update
Metada in Primary Standby
${PGDATA}/
pg_repslot
Update
Wal record
restart_lsn
Replication
Slot
-Ritesh Das
Ensure all wal segments since
restart_lsn is retained.
$PGDATA/pg_wal
WAL Segments
Ritesh Das
REPMGR
-Ritesh Das
○ detects node failures and promotes standby to primary node.
● [Link] is its configuration file.
● Key Features:
○ Node Management: Registers/Unregisters nodes in replication cluster. Also shows the
status of the cluster and node membership information.
○ Replication Setup: We can trigger a clone to setup a new standby server from a primary
server.
○ Failover/Switchover – Using CLI to easily execute switchover and manual/automatic
failover.
○ Monitoring using repmgrd.
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
CONNECTION POOLING
PostgreSQL for Oracle DBAS
-Ritesh Das
Advantages of using PGBouncer:
1. Connection Pooling
• Reduce Connection Overhead
• Reuse Connections
2. Improved Performance and Scalability
• Efficient Resource Utilization:
• Support for High Concurrency
3. Idle Connection Management
4. Increased Reliability
Ritesh Das
PostgreSQL for Oracle DBAS -Ritesh Das
Ritesh Das
PostgreSQL for Oracle DBAS
-Ritesh Das
High availability
Load Balancing
Automatic Failover
HA in PGPOOL-II itself Ritesh Das
DEMO
repmgr
-Ritesh Das
Hostname:
pgpool
Hostname:
Ritesh Das
training_db2
PostgreSQL for Oracle DBAS
18
Database
-Ritesh Das
Maintenance
1. Regular Administration & Maintenance
Activities
2. Managing Bloat
3. Reindex
4. Debugging
Ritesh Das
Regular Administration & Maintenance Activities
-Ritesh Das
● Bloat
● Identifying Unused indexes
● Re-Index
● Stale Statistics
Ritesh Das
Bloat
-Ritesh Das
tuple_len | 121000000
tuple_percent | 88.64
dead_tuple_count | 15782
dead_tuple_len | 1909622
dead_tuple_percent | 1.4
free_space | 1786604
free_percent | 1.31
Ritesh Das
Fixing Bloat
-Ritesh Das
Feature VACUUM FULL pg_repack
Locking Requires exclusive table lock. Non-blocking; allows concurrent access.
Downtime Can cause significant downtime. Minimal downtime; suitable for production.
Binary Built-in PostgreSQL command. Extension (needs to be installed separately).
Use Case Smaller tables or planned maintenance windows. Large tables or production environnents
4. Clustering
Ritesh Das
CLUSTERING A TABLE
-Ritesh Das
Clustered
Empno Ename Dept Empno Ename Dept
EMP Table is clustered by department
5 Eve HR 4 Carol Sales index.
Non-Clustered
4 Carol Sales 1 Bon Engineering Clustering can help reduce this bloat by
physically reorganizing the table data based
1 Bon Engineering 5 Eve HR on an index, which results in contiguous
3 Alice HR 3 Alice HR Ritesh Das
storage of related rows and removal of
fragmented spaces.
Re-Indexing
-Ritesh Das
of tables + index).
● Like Full Vacuum, Re-Index holds an exclusive lock on the index being rebuild,
preventing writes on the indexed table.
● To be scheduled during off business hours or Use CONCURRENTLY.
● Improves performance of query by optimizing the index.
REINDEX can be done at system (all databases), database, table, index level.
Ritesh Das
Debugging
-Ritesh Das
[Link]
Ritesh Das
Parameter Description Possible Values
debug5, debug4, debug3, debug2, debug1,
-Ritesh Das
Logs the duration of each completed SQL
log_duration on, off
statement.
Logs performance statistics of each executed
log_statement_stats on, off
statement.
Controls the amount of detail written in the
log_error_verbosity terse, default, verbose
server log for each message that is logged.
log_lock_waits Logs long lock waits. on, off
Logs the use of temporary files larger than -1 (disabled), 0 (log all temp files), N (log
log_temp_files
the specified size (in kilobytes). temp files larger than N KB)
log_line_prefix Controls the format of log lines. Ritesh Das
Various placeholders for details like
timestamp, user, database, etc.
PostgreSQL for Oracle DBAS
log_line_prefix
By Default it is “%m [%p]” (Time Stamp and Process ID)
-Ritesh Das
%t – timestamp, %p – process id, %l – log line number, %d – dbname, %u – username,
%d – application name, %h – hostname/ip