PostgreSQL DBA Interview Questions
-
What is PostgreSQL?
PostgreSQL is a lightweight, free, and open-source relational database management system. PostgreSQL is used widely across regions and companies and can be used in most popular operating systems.
-
What are the benefits of PostgreSQL?
PostgreSQL excels among other SQL databases for several reasons, including:
1.Robustness that makes it suitable for all kinds of applications
2.Free and open-source
3.Security and reliability
4.Wide variety of data types
5.A big community of users worldwide. -
How connection is established in postgres?
The PostgreSQL server (formerly known as Postmaster) acts as the main supervisor process, listening on a designated TCP/IP port for incoming client connections. Upon receiving a connection request, it spawns a separate backend process to handle that session. These backend processes communicate with each other and other instance components using shared memory and semaphores, ensuring data consistency during concurrent access. Once connected, the client sends queries to its assigned backend process, which then parses, plans, and executes the query. The results are transmitted back to the client over the established connection.
-
Explain the postgres architecture ?
PostgreSQL follows a multi-process architecture, where each client connection is handled by a separate backend process. The PostgreSQL server process (previously known as Postmaster) listens on a specified TCP/IP port for incoming client requests. When a connection request arrives, it spawns a dedicated backend process to handle that session. These backend processes interact with shared memory and use inter-process communication (IPC) mechanisms like semaphores and spinlocks to ensure data consistency. The architecture consists of key components such as shared memory (used for caching and transaction management), background processes (like WAL Writer, Checkpointer, and Autovacuum Daemon), and storage structures (such as tables, indexes, and transaction logs). PostgreSQL employs MVCC (Multi-Version Concurrency Control) to allow multiple transactions to run simultaneously without blocking each other. The WAL (Write-Ahead Logging) mechanism ensures data durability by logging changes before applying them to data files. This modular and process-based architecture enhances PostgreSQL’s scalability, reliability, and performance, making it suitable for both transactional and analytical workloads.
-
What are some important background processes in postgres?
PostgreSQL has several important background processes that ensure smooth database operation:
- Checkpointer – Flushes dirty pages from shared buffers to disk at regular intervals to reduce write overhead.
- WAL Writer – Writes transaction logs (WAL – Write-Ahead Logging) to ensure data durability and crash recovery.
- Autovacuum Daemon – Cleans up dead tuples to prevent table bloat and optimize performance.
- Background Writer – Helps reduce I/O spikes by pre-writing dirty pages to disk before checkpoints occur.
- Archiver – Handles WAL file archiving when continuous archiving is enabled.
- Stats Collector – Gathers database statistics for query optimization and performance monitoring.
- Logical Replication Launcher – Manages logical replication workers for data synchronization between databases.
- WAL Receiver/Sender – Handles streaming replication between primary and standby servers.
These background processes enhance performance, data integrity, and high availability in PostgreSQL.
-
What are the memory components in postgres?
PostgreSQL has several important memory components that optimize performance and manage database operations efficiently:
- Shared Buffers – Caches frequently accessed data pages to reduce disk I/O.
- Work Memory – Allocated per query for sorting and hashing operations.
- Maintenance Work Memory – Used for maintenance tasks like vacuuming and indexing.
- WAL Buffers – Temporary storage for Write-Ahead Logging (WAL) before writing to disk.
- Effective Cache Size – An estimate of how much OS cache PostgreSQL can use for query planning.
- Temp Buffers – Session-local buffers used for temporary tables.
- Kernel Page Cache – OS-level caching that stores frequently accessed data to improve performance.
These memory components help PostgreSQL handle queries efficiently, minimize disk access, and optimize overall performance.
-
what is the maximum file size of table or index in postgres? Can we increase that ?
Max size is 1GB. If a table size is big, then it can spread across multiple files.
-
When wal writer write data to wal segement?
The WAL Writer process writes data to WAL (Write-Ahead Logging) segments periodically to ensure durability and crash recovery. It writes data when:
- WAL Buffers are Full – If the WAL buffer fills up, WAL Writer flushes data to WAL segments.
- Timeout Occurs – It writes at regular intervals (
wal_writer_delay, default 200ms) to prevent data loss. - Transaction Commit – WAL entries are flushed when a transaction commits to ensure durability.
- Checkpoints Trigger – During a checkpoint, WAL data is written and synced to disk for consistency.
-
 When bgwriter writes data to disk?
The Background Writer (bgwriter) writes dirty pages from shared buffers to disk proactively to reduce I/O spikes and improve performance. It operates independently of checkpoints and writes data at regular intervals based on bgwriter_lru_maxpages and bgwriter_lru_multiplier settings. The primary triggers for writing include buffer eviction (when new pages are needed), time-based intervals (
bgwriter_delay), and system workload. By gradually writing pages, it prevents sudden bursts of disk I/O during checkpoints, enhancing PostgreSQL’s overall efficiency and responsiveness. -
What is restore_command?
restore_commandin PostgreSQL is a configuration setting that specifies the command used to retrieve archived WAL (Write-Ahead Log) files during recovery or replication. -
What is the significance of pg_ident.conf file?
Just like we have os authenticated db users in oracle. Here in postgres also we have similarconcept. We can provide mapping of os user and postgres db user inside pg_ident.conf file.
-
What is recovery_target_time?
recovery_target_timeis a configuration parameter in PostgreSQL that specifies the exact point in time to which the database should be recovered during point-in-time recovery. -
What is pg_dumpall?
-
What are some wal related parameter in postgrs.conf file?
max_wal_size → It defines the soft limit for the total WAL segment size. If this limit is reached, a checkpoint is triggered to free up space.
wal_keep_segments → Specifies the number of old WAL segments to retain for standby servers. (Deprecated in newer versions, replaced bywal_keep_size.)
wal_keep_size → Defines the size (in MB or GB) of WAL files to retain for replication before they are recycled.
max_wal_senders = 10 → Sets the maximum number of WAL sender processes that handle streaming replication to standby servers. -
What is a tablespace?
In PostgreSQL, a tablespace is a storage location on disk used to store database objects like tables and indexes. It helps in managing disk usage and optimizing performance by placing data on specific storage devices.
Example of Creating a Tablespace:
-
-
Which parameters controls the behaviour of BGWriter?
The Background Writer (bgwriter) behavior in PostgreSQL is controlled by the following parameters:
- bgwriter_delay → Defines the interval (in ms) between background writer runs (default 200ms).
- bgwriter_lru_maxpages → Sets the maximum number of dirty pages written to disk per bgwriter cycle.
- bgwriter_lru_multiplier → Determines how aggressively bgwriter writes pages based on buffer usage (default 2.0).
-
Does postgres support direct i/o.?
No, PostgreSQL does not support Direct I/O natively. It relies on the operating system’s page cache for disk I/O operations, which improves performance by reducing direct disk access.
-
What is the difference between TRUNCATE and DELETE?
TRUNCATE is faster, removes all rows at once
DELETE removes rows one by one, can use WHERE clause -
What is continuous archiving?
Method of archiving WAL files continuously
Essential for PITR capability -
What is autovacuum in PostgreSQL?
Automated process that removes dead tuples and updates statistics
Essential for maintaining database performance -
What is promote_trigger_file?
promote_trigger_file in PostgreSQL is a file that, when created, triggers the standby server to promote itself to a primary server in a replication setup.
-
How do you create and drop a database in PostgreSQL?
To create a database in PostgreSQL, use the following command:
CREATE DATABASE dbname;To drop a database, use:
DROP DATABASE dbname;Ensure no active connections to the database before dropping it. You can check for active connections using
pg_stat_activity. -
How do you take a hot backup?
To take a hot backup in PostgreSQL using pg_basebackup while the database is running:
-
Enable ARCHIVE_MODE:
Setarchive_mode = onand configurearchive_commandinpostgresql.conf, then restart PostgreSQL. -
Run pg_basebackup:
Usepg_basebackupto take a backup:
-
-
How do you create a user and assign privileges in PostgreSQL?
To create a user in PostgreSQL, use the
CREATE USERcommand:CREATE USER username WITH PASSWORD 'password';To assign privileges, you can grant specific permissions like SELECT, INSERT, UPDATE, etc., using the
GRANTcommand. For example:GRANT ALL PRIVILEGES ON DATABASE dbname TO username;This grants the user all privileges on the specified database. You can also grant table-specific privileges:
GRANT SELECT, INSERT ON table_name TO username; -
How do you take a full database backup using **pg_dump**?
To take a full database backup using
pg_dump, use the following command: -
How do you manage users and roles in PostgreSQL?
-
- Password-Based Authentication – Uses MD5, SCRAM-SHA-256, or plain passwords for user verification.
- Trust – Allows connections without authentication (used for local, trusted environments).
- Peer Authentication – Uses OS user credentials to match PostgreSQL roles (Unix/Linux only).
- Ident Authentication – Relies on an external Ident server to verify the user.
- Kerberos, LDAP, PAM, and SSPI – Supports enterprise authentication mechanisms for secure login.
- Certificate-Based Authentication – Uses SSL/TLS certificates for secure connections.
-
What is the significance of pg_ident.conf file?
The pg_ident.conf file in PostgreSQL is used for user mapping when using Ident or external authentication methods like LDAP, Kerberos, or PAM. It allows mapping OS-level or external usernames to PostgreSQL roles, enabling flexible authentication.
-
What is pg_stat_statements?
pg_stat_statementsis a PostgreSQL extension that records execution statistics of SQL queries for performance monitoring and tuning. -
What are connection limits?
Connection limits in PostgreSQL define the maximum number of concurrent connections allowed per database or user, preventing resource exhaustion.
-
What is primary_conninfo?
primary_conninfo in PostgreSQL is a configuration parameter in
recovery.conforpostgresql.confthat specifies the connection details for a standby server to stream WAL data from the primary server. -
What is pg_stat_activity?
pg_stat_activityis a PostgreSQL system view that shows information about currently active database connections. -
What is recovery.conf?
In PostgreSQL <12, the recovery configuration is managed using the
recovery.conffile.
In PostgreSQL ≥12, recovery is managed usingrecovery.signalfor recovery-related settings andstandby.signalto enable replication. -
What are GRANT/REVOKE?
GRANT/REVOKE in PostgreSQL are commands used to assign or remove privileges on databases, tables, or other objects to users or roles for access control.
-
What is application_name in replication?
application_name in PostgreSQL replication identifies a replica or client connection in the primary server’s
pg_stat_replicationview for monitoring and management. -
What are wait events?
Wait events in PostgreSQL indicate the resource or condition a process is waiting for, helping diagnose performance bottlenecks.
-
What is pg_audit?
pg_audit is a PostgreSQL extension that provides detailed logging of database activities for security and compliance auditing.
-
What is pg_dumpall?
-
What is archive_command?
-
How do you handle bloated tables and indexes?
-
What are the different types of backups in PostgreSQL?
- Logical Backup – Uses tools like
pg_dumpandpg_dumpallto export data in SQL or other formats for selective restoration. - Physical Backup – Copies database files directly using
pg_basebackupor file system-level backups for full database recovery. - Point-In-Time Recovery (PITR) – Combines WAL archiving with a base backup to restore the database to a specific point in time.
- Logical Backup – Uses tools like
-
What is this wal_level parameter , different values of wal_level?
The
wal_levelparameter controls the amount of information written to the Write-Ahead Log (WAL), impacting replication, backups, and point-in-time recovery (PITR).Different Values of
wal_level- minimal → Generates only enough WAL for crash recovery (no replication or PITR).
- replica (default) → Supports streaming replication and PITR, recording changes at the row level.
- logical → Includes additional details for logical replication and decoding (used for logical replication tools).
Â
-
What is visibility map in postgres?
The Visibility Map (VM) in PostgreSQL is a lightweight data structure that tracks which pages in a table contain only frozen tuples (i.e., tuples that do not need further vacuuming). It helps autovacuum and index-only scans work efficiently by reducing the need to scan unnecessary pages.
When a page is marked all-visible in the Visibility Map, PostgreSQL can skip scanning it during vacuum operations, improving performance. Additionally, index-only scans use the VM to determine if they can return results without accessing heap pages, making queries faster. The VM is automatically maintained by vacuum and autovacuum processes.
-
What is log_min_duration_statement?
log_min_duration_statementis a PostgreSQL setting that logs SQL statements taking longer than a specified time, helping in performance monitoring. -
What is SSL certificate authentication?
SSL certificate authentication in PostgreSQL verifies client identity using SSL/TLS certificates instead of passwords, ensuring secure and encrypted connections.
-
What is pg_stat_replication?
pg_stat_replication is a PostgreSQL system view that displays real-time information about active replication connections on the primary server, including lag and status.
-
What are statistics in PostgreSQL?
**Statistics** in PostgreSQL are collected metadata about database objects (such as tables, indexes, and columns) that help the query planner optimize query execution by estimating the cost of different query plans. for a couple of seconds.
-
What is pg_stat_bgwriter?
pg_stat_bgwriteris a PostgreSQL view that provides statistics on the background writer process, helping monitor checkpoint activity and buffer management. -
What is password encryption?
Password encryption in PostgreSQL secures stored user passwords using hashing algorithms like MD5, SCRAM-SHA-256, or plaintext (unencrypted) for authentication.
-
What are default privileges?
Default privileges in PostgreSQL define the automatic permissions granted to users or roles for newly created objects like tables, sequences, or functions.
-
What is pg_stat_database?
pg_stat_bgwriteris a PostgreSQL view that provides statistics on the background writer process, helping monitor checkpoint activity and buffer management. -
What is SSL in PostgreSQL?
SSL (Secure Sockets Layer) in PostgreSQL encrypts client-server communication, ensuring secure data transmission and protection against eavesdropping and man-in-the-middle attacks.
-
How do you list all databases and tables?
To list all databases in PostgreSQL, use the following command:
\l -- or \listTo list all tables in the current database, use:
\dt -
What is visibility map in postgres?
Every heap relation (i.e table/index) have a visibility map associated with them.Every visibility map has 2 bits per page.The first bit, if set, indicates that the page is all-visible (means those pages need not to bevacuumed)The second bit, if set means, all tuples on this page has been frozen. (No need to vacuum) Note – > Visibility map bits are set by VACUUM operation. And if data is modified, bits will becleared.This condition helps in index only scan.
-
What is the difference between **VACUUM**, **ANALYZE**, and **VACUUM FULL**?
-
What is free space mapping (FSM) in postgres?
Each table/index has a Free space mapping file. It keeps information about which pages are free.The VACUUM process also updates the Free Space Map and using VACUUM FULL we canrecover those free spaces.
-
What is track_io_timing?
track_io_timingis a PostgreSQL setting that enables tracking of I/O operation times for query performance analysis. -
What is client authentication?
Client authentication in PostgreSQL is the process of verifying a user’s identity using methods like password, SSL, LDAP, Kerberos, or trust before granting database access.
-
How do you perform a failover in PostgreSQL?
-
What is free space mapping(FSM) in postgres?
The Free Space Map (FSM) in PostgreSQL is a data structure that tracks available free space in table pages. It helps PostgreSQL efficiently find pages with enough room to insert new tuples, reducing the need for table bloat and minimizing random I/O.
FSM is automatically updated during vacuum and insert operations. When a new row is inserted, PostgreSQL checks FSM to locate a page with sufficient free space instead of always appending data to the end of the table. This improves storage efficiency and helps maintain better performance over time.
-
What is pgcrypto?
pgcryptois a PostgreSQL extension that provides cryptographic functions for encryption, hashing, and data security. -
-
Explain Logical Replication vs Physical Replication
-
How does partitioning work in PostgreSQL?
Partitioning in PostgreSQL divides a large table into smaller, manageable pieces (partitions) to improve query performance and maintenance. PostgreSQL supports range, list, and hash partitioning, where data is stored in separate child tables based on predefined rules. The planner optimizes queries by scanning only relevant partitions (partition pruning), reducing I/O and execution time.
-
 Describe the purpose of the pg_isready command in PostgreSQL.What is initial fork?
The
pg_isreadycommand in PostgreSQL is used to check the availability and readiness of a PostgreSQL database server. It helps in monitoring database health and is commonly used in scripts and automated systems to detect if the server is accepting connections. -
How do you enable SSL in PostgreSQL?
-
Explain the role of **WAL (Write-Ahead Logging)** in PostgreSQL.
-
What is TOAST in PostgreSQL?
TOAST (The Oversized-Attribute Storage Technique) is a mechanism in PostgreSQL that stores large values efficiently by compressing and storing them out-of-line in a separate table. It is used when a row exceeds the page size limit (typically 8KB).
When a column, like TEXT, BYTEA, or JSONB, contains a large value, PostgreSQL automatically compresses and moves it to a TOAST table, keeping only a reference in the main table. This helps reduce bloat, optimize queries, and improve performance by keeping frequently accessed data in memory while storing large values separately.
-
What is log_checkpoints?
log_checkpointsis a PostgreSQL setting that logs checkpoint activity, helping monitor database write performance and recovery behavior. -
Explain Row-Level Security (RLS) in PostgreSQL.
-
 Explain the difference between TOAST tables and regular tables in PostgreSQL.
In PostgreSQL, TOAST (The Oversized-Attribute Storage Technique) tables store large column values separately from the main table, while regular tables store all data within the main table heap.
-
What is pg_stat_user_tables?
pg_stat_user_tablesis a PostgreSQL system view that provides statistics on user-defined tables, including tuples read, inserted, updated, and deleted. -
What are index types in PostgreSQL?
PostgreSQL supports various index types, including B-Tree, Hash, GIN (Generalized Inverted Index), GiST (Generalized Search Tree), SP-GiST (Space-Partitioned GiST), and BRIN (Block Range INdex), each optimized for different query types.
-
What is pg_locks?
pg_locksis a PostgreSQL system view that displays information about locks held by active transactions, helping in diagnosing concurrency issues. -
What is the default block size in postgres? Can we set different block size?
The default block size in PostgreSQL is 8 KB. It is defined at compile time using the
BLCKSZparameter.You cannot change the block size for an existing database, but you can set a different block size (between 1 KB and 32 KB) by recompiling PostgreSQL from source with a customBLCKSZvalue. -
What is pgvector?
pgvectoris a PostgreSQL extension for storing and querying high-dimensional vector embeddings, enabling efficient similarity search. -
How does PostgreSQL handle **MVCC (Multi-Version Concurrency Control)?
PostgreSQL uses Multi-Version Concurrency Control (MVCC) to manage concurrent transactions without blocking reads and writes. Instead of locking rows, MVCC creates multiple versions of a record, allowing transactions to access the appropriate snapshot based on their start time. Dead tuples (old versions) are later cleaned up by autovacuum.
-
What is pg_cron?
pg_cronis a PostgreSQL extension that enables scheduled execution of SQL commands using the database’s internal cron-based job scheduler. -
How do you detect and fix database corruption?
-
What happens in the background during vacuuming process?
Background Process During VACUUM in PostgreSQL
When VACUUM runs in PostgreSQL, it performs multiple background tasks to clean up dead tuples and optimize storage without blocking normal operations. It scans table pages to identify dead tuples left behind by UPDATE and DELETE operations. These tuples are then marked as reusable in the Free Space Map (FSM), allowing future inserts to reuse space efficiently.
If AUTOVACUUM is enabled, it runs automatically, adjusting workload based on system activity. VACUUM FULL, however, rewrites the entire table, reclaiming space but requiring more resources. Additionally, ANALYZE can be triggered to update statistics, improving query planner decisions for better performance.
-
What is pg_stat_monitor?
pg_stat_monitoris a PostgreSQL extension that provides enhanced query performance metrics and statistics for advanced database monitoring and analysis. -
How do you monitor and manage autovacuum in PostgreSQL?
Use the pg_stat_progress_vacuum view and autovacuum configuration parameters to monitor and control the automatic vacuum process.
-
What are the different **index types** in PostgreSQL?
PostgreSQL supports several index types to optimize query performance:
- B-Tree Index – Default and most commonly used, ideal for range and equality queries.
- Hash Index – Optimized for exact matches, but less commonly used due to WAL limitations (before PostgreSQL 11).
- GIN (Generalized Inverted Index) – Best for full-text search and JSONB queries.
- GiST (Generalized Search Tree) – Used for geospatial, full-text, and complex data types.
- BRIN (Block Range INdex) – Efficient for large tables with sequentially correlated data.
- SP-GiST (Space-Partitioned GiST) – Supports hierarchical and non-balanced tree structures.
-
What is the significance of search_path in postgres?
The
search_pathin PostgreSQL defines the schema lookup order when executing SQL queries. It allows users to refer to objects (tables, views, functions) without specifying their schema explicitly. When a query is run, PostgreSQL searches for the object in the schemas listed insearch_path, from left to right, until it finds a match.By default, it includes the
publicschema, but it can be customized to prioritize specific schemas. This helps organize database objects, avoid naming conflicts, and enhance security by restricting access to certain schemas. -
What is logical replication?
Logical replication in PostgreSQL allows selective data replication at the table level using a publish-subscribe model for real-time data synchronization.
-
What is pg_partman?
pg_partmanis a PostgreSQL extension that automates the creation and management of table partitioning for improved performance and data organization. -
What is table partitioning?
Table partitioning in PostgreSQL is a technique that divides a large table into smaller, more manageable pieces (partitions) to improve query performance and maintenance efficiency.
-
What is parallel query?
- Multiple workers executing parts of query
- Controlled by max_parallel_workers parameter
-
Difference between pg_log, pg_clog, pg_xlog?
pg_log→ Stores database server logs, including errors, queries, and system messages. This helps in troubleshooting and monitoring database activity.pg_clog(nowpg_xactin newer versions) → Stores transaction commit status information, tracking whether a transaction is committed or rolled back. Essential for transaction recovery and MVCC consistency.pg_xlog(nowpg_wal) → Contains Write-Ahead Logs (WAL), which ensure data durability and help in crash recovery. It records all changes before they are written to disk.
Â
-
 What is ctid?
ctidis a system column in PostgreSQL that uniquely identifies the physical location of a row within a table. It stores the block number and tuple index (offset) within the block, helping PostgreSQL quickly locate rows.Since
ctidchanges when a row is updated or moved (e.g., byVACUUM FULL), it is not a reliable primary key but is useful for efficient row lookups, indexing, and low-level operations like DELETE optimizations. -
What is pg_bouncer?
PgBounceris a lightweight connection pooler for PostgreSQL that reduces overhead by managing database connections efficiently. -
How can you monitor and manage replication lag in PostgreSQL streaming replication?
Calculate replication lag by comparing the current WAL location on the primary with the corresponding location on the standby
-
What is oid?
Every row in postgres will have a object identifier called oid.
-
What is streaming replication?
Streaming replication in PostgreSQL is a process where a standby server continuously receives WAL (Write-Ahead Logging) records from the primary server to maintain real-time data synchronization.
-
difference between oid and relfilenode?
oid(Object Identifier) → A unique identifier assigned to database objects like tables, indexes, and functions. It is stored in system catalogs (pg_class,pg_database, etc.) and remains constant unless the object is dropped and recreated.relfilenode→ Represents the physical file name on disk for a table or index. PostgreSQL usesrelfilenodeto map a relation (pg_class.relfilenode) to its actual storage file in thebase/directory. IfVACUUM FULLorREINDEXis performed, therelfilenodecan change, but theoidremains the same.
-
Difference between postgres.conf and postgres.auto.conf file?
postgres.conf is the configuration file of the postgres cluster. But when we do any config changes using alter system command, then those parameters are added in postgres.auto.conf file.
When postgres starts , it will first read postgres.conf and then it will read postgres.auto.conf file. -
What is the use of **materialized views**?
A materialized view in PostgreSQL stores the result of a query physically on disk, allowing faster retrieval of complex queries. Unlike regular views, it does not update automatically and requires
REFRESH MATERIALIZED VIEWto update data. -
What is effective_cache_size?
**effective_cache_size** is a PostgreSQL configuration parameter that estimates the amount of memory available for disk caching by the operating system and database, helping the query planner optimize queries.
-
What is work_mem?
**work_mem** is a PostgreSQL configuration parameter that sets the amount of memory allocated for operations like sorting and hashing before writing data to disk. for a couple of seconds
-
What is synchronous replication?
Synchronous replication in PostgreSQL ensures that transactions are committed on both the primary and standby servers simultaneously, providing zero data loss but with increased latency.
-
What is Foreign Data Wrapper?
Foreign Data Wrapper (FDW) in PostgreSQL allows access to external databases or data sources as if they were local tables.
-
What is shared_buffers?
-
What is pgAdmin in PostgreSQL?
pgAdmin is a handy utility that comes with the PostgreSQL installation, and it lets you do regular database-related tasks through a nice graphical interface.
-
What is pg_upgrade?
pg_upgradeis a PostgreSQL tool that upgrades databases to a new major version quickly without dumping and restoring data. -
What is timeline in postgres?
Timeline in postgres is used to distinguish between original cluster and recovered one. When we initialize the cluster, the timelineid will be set to 1. But if database recovery happens then it will increase to 2.
-
 What is the default port in postgres?
Default is 5432.
-
What is event trigger?
An event trigger in PostgreSQL is a special trigger that fires in response to DDL events like
CREATE,ALTER, orDROP. -
What is hot_standby?
hot_standby in PostgreSQL allows read-only queries on a standby server while it is applying WAL changes from the primary server, enabling high availability and load balancing.
-
What is difference between pg_cancel_backend vs pg_terminate_backend?
pg_cancel_backend(pid)→ Gracefully cancels a running query without terminating the session. It sends a SIGINT signal to the backend process, allowing it to clean up and stop execution safely. However, the session remains connected.pg_terminate_backend(pid)→ Forcibly kills the backend process, terminating the entire session. It sends a SIGTERM signal, closing all active transactions abruptly, which may lead to rollback.
Key Difference
- Use
pg_cancel_backendwhen you want to stop a long-running query without disconnecting the session. - Use
pg_terminate_backendwhen you need to forcefully disconnect a session, such as in case of blocking transactions or resource-heavy queries.
-
What is the use of pgbench utility?
pgbenchis a benchmarking tool used to test PostgreSQL performance by simulating workloads and measuring transaction throughput. It helps in stress testing, performance tuning, and identifying bottlenecks. Users can run default or custom SQL workloads to analyze system efficiency under different loads -
How can you configure and manage replication slots in PostgreSQL?
Use the pg_create_logical_replication_slot and pg_drop_replication_slot functions to manage replication slots.
-
What is table sampling?
Table sampling in PostgreSQL allows querying a random subset of rows from a table using methods like
TABLESAMPLE SYSTEMorTABLESAMPLE BERNOULLI. -
What is replication slot?
A replication slot in PostgreSQL ensures WAL logs are retained until a replica or consumer processes them, preventing data loss in streaming replication.
-
How can we encrypt specific columns in postgres?
PostgreSQL does not provide built-in column-level encryption, but you can encrypt specific columns using PGCrypto or client-side encryption.
-
How to handle connection issues?
Handle connection issues in PostgreSQL by checking network settings, authentication configurations (
pg_hba.conf), server logs, and resource limits. -
Which utility is used to upgrade postgres cluster?
pgbouncer is used for connection pooling
-
What is Patroni?
Patroni is an open-source cluster management tool for PostgreSQL that automates high availability, failover, and replication using etcd, Consul, or Zookeeper.
-
How to identify slow queries?
Identify slow queries in PostgreSQL using
EXPLAIN ANALYZE,pg_stat_statements, andlog_min_duration_statement. -
What are the popular tools for managing backup and recovery in postgres?
edb bart , barman etc
-
How to handle disk full?
VACUUM FULL
Remove unused indexes
Archive old data -
What are the different types of replication in PostgreSQL?
-
Describe the purpose of the pg_rewind command in PostgreSQL.
The
pg_rewindcommand in PostgreSQL is used to resynchronize a standby or failed primary server with a new primary after a failover. Instead of performing a full base backup,pg_rewindefficiently rewinds the diverged instance by copying only the changed data, making it faster and reducing downtime. -
What is an extension in postgres? Which extensions you have used ?
pg_stat_statements
pg_track_settings
pg_profile
-
How do you set up Streaming Replication?
-
How to kill a session in postgres?
In PostgreSQL, you can terminate or cancel a session using the following functions:
Cancel a Query (without killing the session):
This stops the running query but keeps the session active.
Terminate a Session (forcefully kill the session):
-
How you monitor long running queries in postgres?
we can use pg_stat_activities to track .
-
How to fix high CPU usage?
Fix high CPU usage in PostgreSQL by optimizing queries, indexing properly, tuning configuration settings, and monitoring
pg_stat_statementsfor expensive queries. -
What are **CTEs (Common Table Expressions)**, and how do they work?
Common Table Expressions (CTEs) in PostgreSQL are temporary result sets that simplify complex queries and improve readability. Defined using the
WITHclause, CTEs can be referenced multiple times within a query. They are especially useful for recursive queries and breaking down complex logic. -
What is the role of pg_stat_replication?
pg_stat_replicationis a PostgreSQL system view that monitors replication on the primary server, showing active standby connections, replication lag, and status. Key columns include client_addr (standby IP), state (streaming,catchup), and sent_lsn, write_lsn, replay_lsn (WAL positions). Use it to check replication health:SELECT pid, client_addr, state, sent_lsn, replay_lsn, sync_state FROM pg_stat_replication; -
What is the purpose of the pg_stat_bgwriter view in PostgreSQL?
The pg_stat_bgwriter view in PostgreSQL provides statistics about the background writer process, which helps manage buffer writes to disk. It tracks metrics like checkpoints, buffers written, and WAL sync operations, aiding in performance tuning and monitoring database I/O behavior.
To check bgwriter stats:
-
What is table partitioning in postgres? What are the advantages?
Table Partitioning in PostgreSQL
Table partitioning divides a large table into smaller partitions based on criteria like range, list, or hash. The parent table is a logical structure, while actual data is stored in partitions.
Advantages:
- Faster Queries – Scans only relevant partitions.
- Efficient Data Management – Easy to archive or drop old partitions.
- Better Performance – Improves bulk inserts and deletes.
- Optimized Indexing – Smaller and more efficient indexes.
- Reduced Contention – Enhances concurrency by distributing load.
-
Between postgres and nosql database like mongodb , which one is better?
The choice between PostgreSQL and MongoDB depends on your use case:
 PostgreSQL (Relational DB) – Best for structured data, strong ACID compliance, complex queries, and transactions. Suitable for financial systems, analytics, and applications requiring strict data consistency.MongoDB (NoSQL, Document DB) – Ideal for unstructured or semi-structured data, high scalability, and flexible schemas. Best for big data, real-time apps, and fast-growing applications with schema changes.
Which is Better?
Choose PostgreSQL for reliable transactions, reporting, and complex queries.
Choose MongoDB for scalability, flexibility, and high-speed document-based storage. - Explain the difference between **JSON and JSONB** in PostgreSQL.
In PostgreSQL, JSON stores data as a plain text representation, preserving formatting but requiring re-parsing for each query. JSONB, on the other hand, stores data in a binary format, allowing faster searches, indexing, and efficient storage. While JSON is better for simple storage and retrieval, JSONB is preferred for complex queries and indexing. -
What are some key difference between oracle and postgres?
Oracle is a proprietary, enterprise-grade relational database, while PostgreSQL is an open-source, community-driven database. Oracle offers advanced scalability, partitioning, and multi-tenant architecture, making it ideal for large enterprises and mission-critical applications. It supports PL/SQL for procedural programming, advanced replication options like Active Data Guard and GoldenGate, and enterprise-grade backup and recovery tools such as RMAN.
PostgreSQL, on the other hand, is highly extensible, allowing users to define custom data types, functions, and extensions. It supports PL/pgSQL, along with other languages like Python and Java. PostgreSQL is preferred for modern applications due to its native JSON support, flexible partitioning, and cost-effectiveness. While Oracle provides robust enterprise solutions, PostgreSQL excels in openness, flexibility, and cost efficiency, making it a strong alternative for organizations looking to avoid high licensing costs.
-
How do you create a new database in PostgreSQL?
To create a new database, use the SQL command:
sqlCopy code
CREATE DATABASE dbname; -
How to handle replication lag?
Handle replication lag in PostgreSQL by tuning
wal_sender_timeout, optimizing network performance, increasingmax_wal_size, and monitoringpg_stat_replication. -
How does partitioning work in PostgreSQL?
Partitioning in PostgreSQL divides a large table into smaller, manageable pieces called partitions based on a specified column. It improves query performance and maintenance. PostgreSQL supports range, list, and hash partitioning.
-
While dropping a postgres database i am getting error? What might be the issue?
If you want to drop a database , then you need to fire the command, after connecting to a different database in the same postgres cluster with superuser privilege.
-
How to fix database bloat?
Fix database bloat in PostgreSQL by running
VACUUM (FULL),ANALYZE, usingautovacuum, and implementing table partitioning where necessary. -
What is the pg_dump method used for?
The pg_dump method allows you to create a text file with a set of SQL commands that, when run in a PostgreSQL server, will recreate the database in the same state as it was at the moment of the dump.
-
Explain the concept of roles and privileges in PostgreSQL.
PostgreSQL uses roles to manage user access and permissions. A role can be a user (with
LOGIN) or a group (withoutLOGIN). Privileges define what actions a role can perform, such as SELECT, INSERT, UPDATE, DELETE, CREATE, CONNECT, and EXECUTE. Roles are granted privileges using theGRANTcommand and revoked usingREVOKE. This role-based access control (RBAC) system ensures secure and efficient permission management. -
What is the latest version of postgres in market?
Postgres 15.
-
What is the purpose of the pg_hba.conf file in PostgreSQL?
The pg_hba.conf file specifies client authentication rules, controlling which hosts are allowed to connect to the PostgreSQL server and how they authenticate.
-
How to handle connection pooling?
Handle connection pooling in PostgreSQL using tools like PgBouncer or Pgpool-II to manage and optimize database connections efficiently.
-
How can i check the version of postgres?
cat PG_VERSION file.
or select pg_version();
-
 How do you perform a backup and restore in PostgreSQL?
Use the pg_dump command for backups and the pg_restore command for restores. Example:
bashCopy code
pg_dump -h localhost -U username dbname > backup.sql pg_restore -h localhost -U username -d dbname backup.sql. -
How to fix lock contention?
Fix lock contention in PostgreSQL by identifying blocking queries with
pg_locks, optimizing transactions, using proper indexing, and minimizing long-held locks. -
How pg_repack works internally?
pg_repack reorganizes tables and indexes online without locking writes. It creates a new table, copies data efficiently while tracking changes via triggers, applies modifications, and swaps the old table with the new one. This helps reclaim space and optimize performance without downtime.
-
What is the purpose of the pg_stat_user_tables view in PostgreSQL?
The pg_stat_user_tables view provides statistics about table-level activity and performance
-
Is there a way in which we can rebuild/reorg a table online to release free space?
As we know vacuum full is used to rebuild table and it releases free space to operating system. However this method, puts an exclusive lock on the table.
-
Describe the purpose of the pg_stat_progress_cluster view in PostgreSQL.
The pg_stat_progress_cluster view provides information about the progress of cluster reorganization operations.
-
what is the maximum file size of table or index in postgres? Can we increase that ?
Max size is 1GB. If a table size is big, then it can spread across multiple files. lets says the file_name is 19870 . and once it reaches 1gb, a new file will be created as 19870.1 .
-
How can you implement high availability and failover in PostgreSQL?
Use tools like Patroni or repmgr to set up and manage streaming replication and automatic failover.
-
How to handle index corruption?
Handle index corruption in PostgreSQL by rebuilding the index using
REINDEX, or recreating it if necessary to restore data integrity. -
What are the different datatypes in postgres?
Boolean
char,vchar,
int,float(n)
uuid
date -
Explain the concept of parallel queries in PostgreSQL.
Parallel queries use multiple worker processes to execute parts of a query concurrently, improving query performance.
-
How to improve checkpoint performance?
Improve checkpoint performance in PostgreSQL by tuning
checkpoint_timeout,max_wal_size,checkpoint_completion_target, and monitoringpg_stat_bgwriter. -
Difference between explain and explain analyze in postgres?
Explain – > Generates query plan by calculating the cost
Explain analyze -> It will execute the query and provides query statistics of the executed query. This gives more accurate plan details. Please be careful while running insert,update,delete like DML commands with explain analyze, as it will run the query and cause data changes. -
What is the meaning of PgAdmin?
PgAdmin is a free open-source graphical front-end PostgreSQL database administration tool. This web-based GUI tool is prominently used to manage PostgreSQL databases. It assists in monitoring and managing numerous complex PostgreSQL and EDB database systems. PgAdmin is used to accomplish tasks like accessing, developing, and carrying out quality testing procedures.
-
What is the full form of MVCC?
The full form of MVCC is Multi-version Concurrency Control.
-
Describe the purpose of the pg_xact directory in PostgreSQL.
The pg_xact directory contains transaction status files that track the state of active transactions.
-
What is the full form of GEQO?
The full form of GEQO is Genetic Query Optimization. It enables non-exhaustive search to efficiently manage large join queries in PostgreSQL.
-
What is random page cost?
-
what different types of streaming replications are present in postgres? And which parameters control that.
PostgreSQL supports asynchronous, synchronous, and logical replication. Asynchronous improves performance but risks data loss, synchronous ensures zero data loss by waiting for standby confirmation, and logical replication allows selective table replication.
Key parameters:
wal_level(replica/logical)
max_wal_senders(limits WAL sender processes)(controls commit behavior)
synchronous_commit
primary_conninfo(connects standby to primary
hot_standby(enables read queries on standby) -
 How can you monitor and manage autocommit behavior in PostgreSQL?
Use the autocommit configuration parameter and the BEGIN and COMMIT statements to control autocommit behavior.
-
what is the use of share_preload_libraries in postgres.conf file?
Usually when we add extensions like pg_stat_statement, then we need to add the library path in the parameter shared_preload_libraries.
Because these extensions use shared memory, we need to restart the postgres cluster.
the reason we are preloading these libraries is to avoid the library startup time, when the library is first used. -
Explain the concept of logical replication in PostgreSQL.
Logical replication replicates data changes using a publish-subscribe mechanism at the row level.
-
What are foreign data wrappers? What is its use?
Foreign Data Wrappers (FDW) allow PostgreSQL to access external databases as if they were local tables. They use the SQL/MED (SQL Management of External Data) standard to fetch data from sources like other PostgreSQL instances, MySQL, MongoDB, or even CSV files.
-
Describe the purpose of the pg_resetxlog utility in PostgreSQL.
The pg_resetxlog utility is used to reset the write-ahead log (WAL) and recover from severe corruption.
-
Difference between role and user in postgres? Can we convert a role to user?
Role and user are almost same in postgres, only difference is , a role cannot login , But a user can. We can say like a user is role with login privilege.
And yes we can convert the role to a user.
alter role <role_name> nologin; -
What are the default databases created after setting up postgres cluster?
postgres=#Â select datname from pg_database;
datname
———–
postgres
template1
template0 -
What is the use of temporary tablespace?Â
A temporary tablespace in PostgreSQL is used to store temporary objects like temp tables, sorting operations, and hash joins. It helps improve performance by preventing temp data from consuming the main tablespace. You can assign a temporary tablespace using:
-
How can you implement data encryption in PostgreSQL?
PostgreSQL supports encryption via PGCrypto for column-level encryption, SSL for secure connections, and disk-level encryption using LUKS or filesystem tools. Transparent Data Encryption (TDE) requires third-party solutions.
-
Explain the concept of full-text search in PostgreSQL.
Full-text search allows you to search for words or phrases within text documents stored in the database.
-
What is vacuum?
In PostgreSQL, VACUUM is a maintenance operation that removes dead tuples, frees up space, and updates visibility maps to optimize database performance.
-
What tools do you use for monitoring PostgreSQL performance?
-
What are the tablespaces created by default after installing postgres cluster?
After installing a PostgreSQL cluster, two default tablespaces are created:
- pg_default – Stores user-defined tables, indexes, and other database objects by default.
- pg_global – Stores shared system catalogs that are accessible across all databases in the cluster.
These tablespaces manage database storage unless additional tablespaces are created.
-
What is analyze?
In PostgreSQL, ANALYZE collects statistics on table data distribution to help the query planner generate efficient execution plans.
-
How do you check the current connections and terminate a session?
To check current connections in PostgreSQL, query
pg_stat_activity:To terminate a specific session, use:
For immediate termination, use:
-
What are common causes of deadlocks, and how do you resolve them?
-
How do you handle bloated tables and indexes?
-
Describe the purpose of the pg_wal directory in PostgreSQL.
The pg_wal directory in PostgreSQL stores Write-Ahead Logging (WAL) files, which ensure data durability and crash recovery. WAL records all changes before they are written to disk, allowing PostgreSQL to recover uncommitted transactions after a crash. It also plays a key role in replication and point-in-time recovery (PITR).
-
How do you check for long-running queries?
Use the following query to check long-running queries in PostgreSQL:
SELECT pid, age(clock_timestamp(), query_start) AS duration, state, query FROM pg_stat_activity WHERE state = 'active' ORDER BY duration DESC;
-
What is the use of EXPLAIN ANALYZE?
-
How do you perform Point-In-Time Recovery (PITR)?
To perform Point-In-Time Recovery (PITR) in PostgreSQL, first take a physical base backup using
pg_basebackupor by copying the data directory. Enable WAL archiving by settingarchive_mode = onandarchive_command. To restore, stop the database, replace data files with the base backup, and configure recovery settings inrecovery.conf(orpostgresql.auto.confin newer versions) withrestore_commandandrecovery_target_time. Restart PostgreSQL, and it will replay WAL logs up to the specified point, ensuring precise data recovery. -
What is the purpose of **pg_hba.conf**?
-
How do you optimize query performance in PostgreSQL?
-
How do you restore a corrupted database?
-
What is the purpose of the pg_basebackup command?
-
 Why is postgres OPEN SOURCE DATABASE?
-
What are the features of EDB POSTGRES ADVANCED SERVER?
-
What features does postgres provide under Security?
-
Can you tell me about the Postgres database Limit?
Maximum Database size — Unlimited.
Maximum Table size —32TB.
Maximum Row Size—1.6TB.
Maximum Field Size–1 GB.
Maximum Rows per table= Unlimited.
Maximum coloumns per table —250 to 1600 (Depending on column types.)
Maximum indexes per table –Unlimited. -
-
What is MVCC? How Does PostgreSQL Handle Concurrency?
MVCC:
MVCC allows multiple transactions to read and write to the database at the same time without interfering with each other while each transaction operates on a “snapshot” of the database which is a consistent view of the data at a specific time. For example: If one user tries updating a particular row record and at the same time another user tries to update the same particular record. Then before when user 1 starts transaction, it creates a snapshot of the record. Also with another user, same thing will happen before the 2nd user starts transaction, PostgreSQL will create a snapshot. Now if user 1 updates the record, then that record will become the current version. Now when user 2 tries to update, he will get serialization error as the data was already changed by user 1. So user 2 will have to refresh and once user 2 refreshes, he will see the updated record and after that he can update to whatever value he wants. That’s how MVCC technique works. There are different concurrency control techniques including Timestamp-based concurrency control, Lock-based concurrency control, and Multiversion Concurrency Control (MVCC). MVCC is a widely used approach.
-
What is WRITE AHEAD LOGGING?
-
How does the SQL STATEMENT Process in POSTGRESQL Database?
Each user has a backend dedicated POSTGRES Process which is responsible for processing SQL queries received from the users. When a client sends a SQL query to the server, the query must go through SQL engine. SQL engine is a part of a backend POSTGRES Process. Inside the SQL Engine, it has various phases that the SQL query needs to go through.
1) Parsing:Â Parser verifies the syntax of the query. Based on the type of query, the query may or may not require optimization. If not, then query will run through the command processor directly. And if the query requires Optimization, we need to ensure we break down the query into tokens and validate the token. The tokens are object names like column name or table names and we need to ensure those column and table names are available in our PostgreSQL database. And the user has required permission to access those objects. All of these are done during the Parsing stage. After the Parsing Query is sent to the optimizer who is going to work on the query and create an execution plan.
2) Optimization:Â During Optimization phase, a planner generates the query plan based on the statistics and planner parameters. The query planner creates a query plan based on the database statistics and configuration settings. The planner estimates the cost of random page scans using the RANDOM_PAGE_COST Parameter. If you are using Optimizer hints in the query those may be applied at the time of optimization. After that query or plan cost will be calculated and based on the cost. A low cost plan will be chosen. After this the query with optimized plan is sent to the Executor for execution.
3) Execution:Â Executor executes the query and the result set is sent back to the user. This is how SQL engine works for each query in PostgreSQL.
-
What does Postgresql.conf file store?
-
What is PG_HBA.conf file?
The IP address authentication is done by using PG_HBA.CONF File.
-
What is PG_IDENT.conf file?
It is used to perform operating system authentication.
-
What is a page in PostgreSQL?
A page in PostgreSQL is the smallest storage block on the disk. A page stores data for a table as well as its indexes. It can be Index page or a normal data page. A page is 8 Kilobyte in Size. There is page header at the top which stores general information about the page. Then we have ITEM pointers some of which are pointing to the tuples on the page. At the end of the page there is a special space. In normal pages, this space may be empty or may store the index access method for specific data. This is the complete layout of an 8KB PAGE in PostgreSQL.
-
What is Database cluster in PostgreSQL?
A database cluster is a collection of databases managed by a single server instance.
-
What is Database cluster in PostgreSQL?
A database cluster is a collection of databases managed by a single server instance.
-
What does PG_CONTROLDATA store?
It can be used to view the control information of the database cluster. This utility is useful in case you have a data directory and you are trying to find out the database version or the block size or the WAL level settings or various other settings including checkpoint information or whether the server is up and running or not. PG_CONTROLDATA utility shows detailed control information about a data directory.
-
How do we access Tablespace in PostgreSQL? Where is the data stored in PostgreSQL?
Internally in the cluster, there is a link between a tablespace and a physical location on disk where the data is stored.
-
What is Catalog?
Within a database, we have catalogs. It keeps a track of the objects within our database. The catalog is a series of database tables that keep track of our database objects as well as keep track of internal processes and statistics.
-
What is role in PostgreSQL Cluster?
Role is a collection of privileges. It is an easy and effective way to assign database permissions to a large group of people.
-
What is schema?
It is a logical container of objects that belongs to a database such as tables, views, sequences and functions. So when you create a database, 2 things happen internally: first the cluster goes out and creates a directory in one of the following 3 places:
-
In the Tablespace, I specify on the create database statement.
-
In the default tablespace defined in the PostgreSQL configuration file.
-
In the PG_TBLSC tablespace.
Secondly it creates a schema called public to collect any database objects I create. To Summarise, Schemas are used to logically collect your objects and bundle them together in one schema and assign an ownership to a particular database user.
-
-
What does parameter Work_mem do? Why SQL queries in PostgreSQL may be slow even for indexed tables?
Queries against large sets of table rows may need a lot of memory to sort, join, aggregate, or subselect data. PostgreSQL uses the value of work_mem setting as the limit on how much memory each query may use for each sorting operation or hash table. The default value for work_mem is 4MB. If sorting or hash table needs more memory than permitted by work_mem, then PostgreSQL will use temp files on disk to perform such operations. Since disk IO is much slower than memory IO, such heavy queries may become increasingly slow as the number of rows in the dataset grows, even though the query may use indexes efficiently.
-
How can I tell if a query is slow because it actually uses temp files?
To find out, just run EXPLAIN ANALYZE for that query against the production database server and have a look at its output (the query execution plan). If you see lines like Sort Method: external merge Disk:Â <XXXX>kB then it is definitely happening. Higher work_mem value may make such queries faster if it allows to fit all the temp data for the query into memory.
-
What is Dynatune?
Dynatune runs at the time of Database start, checks for the available memory and expected workload type and then sets the database parameters in postgresql.conf file to a tuned value. We can control the resource limit and workload type for Dynatune using 2 Parameters. These parameters changes are applied during a server restart.
-
EDB_DYNATUNE parameter is used to specify a limit on the resources that can be used by database server.
-
EDB_DYNATUNE_PROFILE can be set to OLTP or reporting or mixed based on the type of workload expected on the database.
-
-
What is the role of BG WRITER background process?
Every database cluster has BG Writer background process which helps in dirty buffer sync to data files. The process automatically starts at the server start and performs data buffer sync continuously. By Default, the background writes 100 Buffers to the disk in a roundtrip. It takes a pause of 200 milliseconds after finishing its work before going for another round trip. This behaviour can be customized using the BGWRITER_DELAY & BGWRITER_LRU_MAXPAGES parameters.
-
Does PostgreSQL support Parallel query scan?
PostgreSQL supports Parallel query. The query planner must create a query plan for each query that is received by a database cluster. During query planning, the planner may decide to use multiple processes to perform Table scan or index scan in parallel. This is called parallel scan and can speed up the query execution. The Planner must calculate the overall cost for a plan with parallel scan and decide the number of processes that can be launched simultaneously to perform a Table or an Index Scan. You can control the Planner’s behaviour for Parallel Scan using the available list of Parameters. You can set the maximum number of Parallel workers per user session using the MAX_PARALLEL_WORKERS_PER_GATHER parameter. Planner cost for scanning each tuple in Parallel and Parallel scan set up can be set using PARALLEL_TUPLE_COST parameter.
-
What is AUTOVACUUM?
Autovacuum is done automatically by the PostgreSQL database. For that the parameter autovacuum should be ON. By default it is ON.
Autovacuum can be used to automate vacuuming tasks like Vacuum, Analyze, and Vacuum freeze. The Autovacuum process starts autovacuum workers. The autovacuum workers processes perform Vacuum, Analyze, and Vacuum freeze based on set thresholds. You can turn the autovacuum process ON or OFF using autovacuum parameter. Slow Autovacuum workers can be traced using LOG_AUTOVACUUM_MIN_DURATION. AUTOVACUUM_MAX_WORKERS can be used to set the number of Autovacuum workers that can run for a database cluster. Please note that only one table can be maintained by one autovacuum worker after which it has to go for Sleep which is set using AUTOVACUUM_NAPTIME parameter. Each worker is assigned a memory for performing Set maintenance tasks. And the memory limit can be set using AUTOVACUUM_WORK_MEMORY parameter.
What is Vacuum?
Vacuum is used to free up dead tuples in a table so that they can be re-used. Whenever a record is deleted, it creates what is called Dead tuples. It doesn’t create any extra space. If there is no more dependency on those tuples by the running transactions, PostgreSQL cleans it up using a process called Vacuum. Remember it doesn’t return the disk space back to the OS, but it will make it usable for new rows. When you do Vacuum Full? The process takes a lot of compute i.e. CPUs and Memory. It will return back the storage to the Operating System. When you do Vacuum Full, it will lock the table (blocking all the operations) including the SELECT statement. When you do Vacuum Full, it will create a copy of a table that will double up the storage requirement. Only if you have enough storage then go for Vacuum Full.
-
What is JUST IN TIME (JIT) Compilation?
A feature that was originally introduced in PostgreSQL 11, just-in-time compilation is now enabled by default in PostgreSQL 12. Just-in-time compilation allows for data warehouse queries that process lots of data to run the executor more efficiently. Because many users turned this feature on, it’s now become the default for PostgreSQL 12.
OR
JIT compilation can be used to speed up accelerating expression evaluation and tuple deforming. Basically it is a core feature of EDB PostgreSQL for accomplishing high performance. You can control and customize JIT behaviour using various JIT Parameters. Please note that the JIT package must be installed edb-as14-server-llvmJIT for using JIT features of PostgreSQL.
-
Which parameters in PostgreSQL are permanent and cannot be changed?
Block_Size, Wal_block_size, Segment_size, Wal_segment_size, Data_checksums, server_encoding, ssl_library, etc.
-
When FSYNC is turned off what can happen?
The Fsync parameter forces a WAL Buffer flush at each commit. Turning it off can lead to an Arbitrary corruption in a system crash case.
-
Why does the query run slow?
Below are the reasons:
FULL TABLE SCAN:Â A query runs slow when it does FULL TABLE SCAN. If you are searching for data in a large table without any index, it can lead to a sequential scan.
BAD SQL:Â This can also happen if there is a high amount of duplicate values or the table statistics were not updated after a bulk operation on the Table.
OLD OR MISSING STATISTICS:Â Old or missing statistics itself can cause a magnitude of issues for the planner, which can lead to old or stale query plans.
SORT USING DISK:Â In PostgreSQL the WORK_MEM parameter controls the maximum memory available to a session for performing Sort and hash operations. If this parameter is not tuned to an appropriate value, it can lead to the sort and hash spilling onto the disk.
There are other types of common issues that can slow down a query like Join Orders, Bad connection Management, Disk or network issues.
-
What are the SQL TUNING STEPS?
Identify Slow queries → Review the query execution plan → Review optimizer statistics & Behaviour → Restructure SQL statements → Add or remove indexes → Review Final Execution plan.
-
How to Identify slow queries?
We can use LOG_MIN_DURATION_STATEMENT parameter or monitoring tool called PostgreSQL Enterprise Manager for tracking slow queries.
LOG_MIN_DURATION_STATEMENT is a configuration parameter which can be set to a time in milliseconds. Any query that runs longer than the specified time is tracked and written to the PostgreSQL error log with its duration as well as any other information prefixed to it using LOG_LINE_PREFIX parameter.
-
What is PG_STAT_STATEMENTS extension?
PG_STAT_STATEMENTS is a PostgreSQL extension and is a part of Contrib packages of PostgreSQL. It is an open source tool available for tracking queries and execution statistics across all databases of a cluster.
-
Explain Analyse command and Explain Command?
Explain Analyze command will show the execution plan. It provides the execution and planning time at the bottom. And it is important to pay close attention to memory buckets and disk usage when using Explain Analyze.
-
What is the use of ANALYZE command?
After vacuum activity, when the dead tuples are removed, after that please run the ANALYZE command. It will gather and update all the statistics of the table. Analyze is going to analyze the table and that will be used by the query optimizer so that it can pick up the latest statistics of the table.
Updating Planner statistics is one of the most critical tasks on your database server. Table statistics can be updated using ANALYZE Command which can also be run using Automatic maintenance process called autovacuum. The syntax of ANALYZE can be run by a Table owner or a superuser. ANALYZE can be run for a single column, table or all the tables in a user’s search_path. Manually update the statistics for all the objects in edbstore database in the given example:
\c edb ANALYZE;
-
What is PG_BADGER tool?
PG_BADGER tool is an open source “fast PostgreSQL log analysis report” program or log analyzer tool. It reads log from a running PostgreSQL and prepare and processes a HTML report. The report is in Human readable format and very good looking. It reports everything about your database. For example: It tells you-
About CONNECTION: How many connections established, connection per database, connection per host, etc.
About SESSION: Session per user, session per host, etc.
About temporary files: Number of temp files and size of temp files information.
About Vacuum activity information.
About locks statistics.
About top wait events.
Before using pg_badger you must enable and set some configuration parameters related to LOGS. We can analyze the pgbadger report on daily basis for review and plan for continuous improvements on database performance area. To get more information from your log files, enable below parameters in Postgresql.conf file.
log_checkpoints = ON log_connections = ON log_disconnections = ON log_lock_waits = ON log_temp_files = 0 log_statement = OFF (It will be OFF as its log format will not be parsed by PGBADGER) log_min_duration_statement = 10 (any statement which is running above 10 Milliseconds will be visible in the report)
-
What are the 2 tablespaces created by default? And can we move objects (table) from one tablespace to another tablespace?
-
PG_GLOBAL tablespace:Â It is used for Shared System catalogs.
-
PG_default tablespace:Â It is the default tablespace of the template 1 and template 0 databases.
Command:
ALTER TABLE ALL IN TABLESPACE tbs1 SET TABLESPACE pg_global;
-
-
What is Bloat in PostgreSQL?
Bloating in database is created when tables or indexes are updated, an update is essentially a delete and insert operation. The disk space used by the delete is available for reuse but it is not reclaimed hence creating the bloat. Same is the case with PostgreSQL database, frequent UPDATE and DELETE operations can leave a lot of unused space in table or index relation files on disk. Over the time this space can build up and cause the performance degradation for both tables and indexes. This buildup is referred to as bloated tables or indexes.
The old version of any row that is affected by an operation like UPDATE or DELETE in PostgreSQL is marked internally so that queries don’t return that row. Therefore, these rows are referred to as “dead rows”, and the space occupied by dead rows is called “bloat.” A database program that often executes a lot of UPDATE/DELETE operations can quickly become very large and require sporadic maintenance work.
What are the ways to remove Bloat?
–VACUUM FULL
VACUUM FULL will remove all bloat in a table and its associated indexes completely and will reclaim the disk space to OS. This will reduce the on disk table size. It does all that with rewriting the whole table, however this is an expensive operation and it will lock the table or index for the duration of this operation, this is not desirable in most situations.
–pg_repack
This is an extension that is helpful in situations where VACUUM FULL or CLUSTER might not work. This extension restructures the table by creating a completely new table based on the data of the bloated table. While tracking the changes being made to the original table and will swap the new table with the original in the end.
This method does not lock the table for any read or write operations and considerably faster than VACUUM FULL or CLUSTER commands. Note: You can run PG_REPACK command for a particular table or all on Full database.
–REINDEX
This option can be used to remove the bloat from indexes.
What Problems BLOAT may cause to PostgreSQL?
— The performance of the database will not be optimum.
— The statistics of the table will not be accurate.
— The query execution plan may get inaccurate due to wrong stats of the table.
-
Difference between Vacuum Full and Vacuum?
2 types of Vacuum – Standard Vacuum and Vacuum Full.
Plain vacuum does not incur exclusive locks, allowing it to run concurrently with regular reading and writing of the table. This type of vacuum operation will keep the additional space accessible for reuse inside the same table, rather than returning it to the operating system. The operating system receives the excess space back when using the VACUUM FULL form, which also rewrites the whole contents of the table onto a new disk file with no extra space. This form must be processed with an ACCESS EXCLUSIVE lock on each table, which makes it slower.
So what does Vacuum do? It frees up dead rows for reuse. It doesn’t use Access Exclusive lock on the tables. Free space is made available inside the table for re-use.
What does Vacuum Full do? It will rewrite the table with no dead rows. It puts an Access Exclusive Lock on the tables. And it frees up the space in the Operating System.
OR
Since vacuum is a routine maintenance of the database system, after the system is started, an autovacuum daemon will be started to deal specifically with this. The autovacuum cleaning process generally uses vacuum instead of vacuum full.
When vacuum full starts to execute, the system will first create an AccessExclusiveLock on the target, which does not allow outside access (preparation for later copy), and then create a new table with the same table structure as the target table. It puts a lock on the table and indexes.
-
Vacuum full will lock the table, vacuum will not.
-
The vacuum just converts the space of the dead tuple row into a usable state. The vacuum full will move the data behind these space fragments up.
-
-
Difference between Vacuum Full & Vacuum Freeze?
VACUUM FULL will remove all bloat in a table and its associated indexes completely and will reclaim the disk space to OS. This will reduce the on disk table size. It does all that with rewriting the whole table, however this is an expensive operation and it will lock the table or index for the duration of this operation, this is not desirable in most situations.
VACUUM FREEZE: Vacuum freeze is a special kind of vacuum which marks rows as Frozen. This process deals with the Transaction Wraparound Problem by freezing old transactions, preventing them from being affected by transaction ID wraparound. It is normally managed by the autovacuum process but can also be run manually.
-
How many connection limits does PostgreSQL 14 have?
In PostgreSQL, the default limit of concurrent connections is 115, with 15 reserved for superusers and 100 available for regular users. However, users can increase the connection limit according to their needs.
-
Features in 15 Version of PostgreSQL?
Removal of the CREATE permission on the PUBLIC schema
Prior to version 15, all users were given CREATE and USAGE access by default in the PUBLIC schema, which posed a security risk. This risk is mitigated in the new release, since only the database owner has default rights to the CREATE and USAGE privileges in the PUBLIC schema.
PG_CHECKPOINT Privilege has been introduced in case if a user wants to run the Checkpoint command, he is required to have PG_CHECKPOINT Grant. For example:
GRANT pg_checkpoint TO USER1;
Default value of the log_checkpoints parameter changed to ‘on’
Prior to version 15, the log_checkpoints parameter in postgresql.conf was set to ‘off’ by default. This default setting has been changed to ‘on’ now.
Enhancement in pg_basebackup
As we all very well know, pg_basebackup is important for taking a base backup of a PostgreSQL cluster. The new version introduces these enhancements.
Option – Target / Option – Compress
-
To recover Disk space occupied by updated or deleted rows (tuples).
-
To Update data statistics used by query planner.
-
To update visibility map, which speeds up index only scans.
-
To protect against loss of very old data due to transaction ID wrap around or multitact ID wrap around which says if your transactions in your database cross 200 Millions then you need to perform the Vacuum.
Why is Vacuum required?
It is required because of the following reasons:
1. To recover Disk space occupied by updated or deleted rows (tuples):
In PostgreSQL, whenever a row is updated or deleted, the old version of the row is not immediately removed from the disk. It is marked as “dead” but still occupies space. Vacuum reclaims this space so it can be reused for new rows.2. To Update data statistics used by query planner:
Vacuum (specifically the ANALYZE part) updates the statistics about the data distribution in tables. The query planner uses these statistics to generate efficient execution plans. Without updated statistics, the planner may choose poor plans, leading to slow queries.3. To update visibility map, which speeds up index only scans:
Vacuum updates the Visibility Map, which tracks which pages contain only “live” (visible) tuples. This allows PostgreSQL to perform Index-Only Scans more efficiently by skipping the heap check when all tuples on a page are visible.4. To protect against loss of very old data due to transaction ID wraparound:
PostgreSQL uses 32-bit transaction IDs. When the transaction ID counter wraps around (after approximately 2 billion transactions), old data may become invisible or the database may shut down to prevent data corruption. Vacuum (specifically VACUUM FREEZE) marks old rows as “frozen” to prevent this. If your transactions in your database cross 200 million, you need to perform the Vacuum.
-
-
What is PG_VISIBILITY MAP used for?
-
How does the structure of the Tuple (Row) look like?
Each File is Divided into Multiple pages. Each page size will be generally 8KB. The data or the records of the tuple comes and sit into the Pages. Each page will have a Page header and also the Item Id pointer. There will be tuples inside the page.
-
T_XMIN ID:Â It is a transaction ID that inserted the tuple.
-
T_XMAX ID:Â It is a transaction ID that deleted or updated the tuple.
-
T_CID (T_FIELD3):Â Position of this command within the current transaction.
-
T_CTID:Â Tuple Identifier that points to new tuple or itself.
Demo:
CREATE TABLE emp (name varchar); -- Transaction ID will be 1 INSERT INTO emp VALUES ('Adil'); -- Transaction Id will be 2. SELECT lp AS tuple, t_xmin, t_xmax, t_field3 AS t_cid, t_ctid FROM heap_page_items(get_raw_page('emp', 0)); --This command will show TUPLE information.
Output:
Tuple t_xmin t_xmax t_cid t_ctid 1 1 0 0 (0,1)
Now If delete command is invoked then see what happens:
DELETE FROM emp WHERE name='adil'; SELECT lp AS tuple, t_xmin, t_xmax, t_field3 AS t_cid, t_ctid FROM heap_page_items(get_raw_page('emp', 0)); --This command will show TUPLE information.
Output:
Tuple t_xmin t_xmax t_cid t_ctid 1 1 2 0 (0,1)
Note: Transaction 1 ID has been deleted so T_XMAX transaction ID became 2. T_CTID will show where it is pointing. Remember when you delete TUPLE will be invisible. It will not be seen but it will be there.
You can run the UPDATE command and check. For example:
UPDATE emp SET name = 'Rehan' WHERE name = 'Adil'; SELECT lp AS tuple, t_xmin, t_xmax, t_field3 AS t_cid, t_ctid FROM heap_page_items(get_raw_page('emp', 0)); --This command will show TUPLE information.
Output:
Tuple t_xmin t_xmax t_cid t_ctid 1 1 2 0 (0,2) 2 2 0 0 (0,2)
Note: As the tuple 1 transaction ID got updated. T_XMAX will be updated with a Tuple 2 transaction ID. t_CTID will point to updated tuple 2. Remember when it is updated the new tuple will be shown in the above scenario — TUPLE 2 is the new tuple and t_CTID will show the pointing towards new Tuple.
So when you vacuum it will free the dead tuple. It will not allocate that space or release that space to disk. That tuple space will be there for further insertion of new records.
So vacuum will delete the data from the row and keep the row unused. Those freed space can only be used when new records are inserted.
VACUUM emp; VACUUM FULL emp;
-
-
What is C-LOG and the transaction snapshot in PostgreSQL?
C-LOG is nothing but area in memory where the status of all the transactions are maintained. It is just like an array in memory. For this C-LOG initially one page of 8KB is allocated. Transaction ID and status of the transaction (Committed, abort, in Progress) will be maintained in the form of array. In older versions, files were written to PG_CLOG directory. From version 10, it writes to PG_XACT directory.
And Transaction snapshot is a data set which shows the details of the transaction at a given point of time. It will show T_XMIN and T_XMAX past and current information of the database.
-
What is transaction ID? What is Transaction ID Wraparound? How to prevent transaction ID wraparound and failures?
Transaction ID is just an ID that moves along 32 BIT INTEGERS and when it gets to the end it goes back to 1 and goes over again and wraps around all the time. So the problem is when we wrap around. So transaction IDs are 32 Bit integers and only half of those transaction IDs are visible. That’s roughly like about 2 billions amount of transaction ID we got. That’s a big number right or maybe not for a database which has a lot of High write intensive workloads can easily exhaust those Transaction ID limit.
If you consume 100 Transaction IDs per second, then you got 8 months. And If you use 1000 Transaction IDs per second then you will have only 24 days to wrap around.
TRANSACTION ID WRAPAROUND That’s the biggest fear of everyone using PostgreSQL.
So basically we have 4 bytes to represent each transaction ID. And of course 4 bytes it means like half of it is roughly 2 Billion. Full will be slightly more than 4 billion.
And on your database if you have 1000 transactions per second, it will take roughly one month. Depends on how stable your traffic is, your workload is. Each tuple physical row version has XMIN, XMAX, CTID.
Every row that is updated in the database in PostgreSQL receives a transaction ID (Txid) from the transaction control mechanism. These IDs regulate which rows are shown to other active transactions. The issue with transaction wraparound is Multi-Version Concurrency Control (MVCC). The ability to distinguish between two transactions based on their Txids is essential for MVCC. Txids in PostgreSQL are just 32-bit integers. Accordingly, there are only roughly four billion (2^32) possible Txids.
Four billion may seem excessive and difficult to achieve, but I must admit that for database systems with really high write-intensive workloads, four billion transactions are achievable in a matter of weeks. Therefore, PostgreSQL stops allowing WRITE operations and switches the database to READONLY mode if there are 2,000,000,000 unvacuumed transactions.
So because of Transaction wraparound, database goes into READ ONLY Mode.
OR
Eventually, that database is going to reach a situation where the XID counter has reached its maximum value. The absolute peak is something around 2 billion, but it can be far
-
What is Visibility map & Free space map?
- What is max_connection? If Max connection has already achieved What action will you take?
- What is connection pooling?
-
What is Watch Dog?
-
What is Forking in PostgreSQL?
-
What is PG_repack?
- What is a password file in PostgreSQL database?
- When do we use PG_RESTORE and PSQL Utility in backups?
- What is Logical backup and physical backup?
- What is PG_BASEBACKUP utility used for?
- How to perform Point in Time Recovery?
- What is the concept of Reverse engineering?
- What is streaming/physical replication?
- What is HOT STANDBY & Warm standby?
- How does Logical replication works/ architecture?
- What are the steps that we follow in LOGICAL Replication?
- What are the Logical replication criteria?
- What is log_statement parameter?
- What is the most common issue with streaming replication going out of sync?
- What are the methods that PostgreSQL supports for logging server messages?
- What is PG_STAT_ACTIVITY view used for?
- What is pg_stat_statements view used for? How to install pg_stat_statements extension?
- What is DRITA stands for and usage?
- What is the use of TIMED_STATISTICS parameter?
- What is pg_bench in PostgreSQL?
- What is TPC-B in pg_bench?
- What is PG_BACKREST?
- What is stanza?
- What is the use of DELTA in restoration using pgbackrest?
- Explain the concept of RTO and RPO?
- How pg_basebackup works in background?
- Which parameters to look for while using pg_basebackup?
- Why tune Shared Buffers in PostgreSQL?
- Why not over-allocate shared buffers?
- What is work_mem?
- When to tune work_mem in PostgreSQL?
- How to make autovacuum aggressive?
- How to tune PostgreSQL for memory?
- What is REPMGR?
-
What is Barman?
Barman the name denotes the Backup and recovery management tool for PostgreSQL server. With Barman, you can create backup on same server, on a different server, on a different dedicated backup server, etc.
-
Logical and Physical replication differences?
In physical replication, it will replicate all the databases. You can’t choose the specific database for replication. And it can not replicate 2 different major versions or platforms for eg from windows to linux. Not possible in physical replication.
Logical replication is more about replicating data objects.
-
Important concepts of Replication:
-
sent_lsn/sent_location:Â Last transaction location sent to standby.
-
write_lsn/write_location:Â Last transaction written on disk at standby.
-
flush_lsn/flush_location:Â Last transaction flush on disk at standby.
-
replay_lsn/replay_location:Â Last transaction flush on disk at standby.
-
write_lag:Â Elapsed time during committed WALs from primary to the standby (but not yet committed in the standby).
-
flush_lag:Â Elapsed time during committed WALs from primary to the standby (WAL’s has already been flushed but not yet applied).
-
replay_lag:Â Elapsed time during committed WALs from primary to the standby (fully committed in standby node).
-
-
How is query cost is calculated?
Cost = number of pages * seq_page_cost (parameter) + number of rows in a table * Cpu_tuple_cost (parameter).
-
Can we disable autovacuum for a particular table?
Yes we can. For eg:
ALTER TABLE emp SET (autovacuum_enabled = false);
-
Does autovacuum do analyze on every table if enabled?
Yes it does. Analyze command would just gather all the stats of the table and give to the optimizer. And during explain plan statement the gathered statistics will give the right value for cost, rows fetched, etc.
-
What is Replication slot?
Replication slot is a useful mechanism to keep a track of WAL which are yet to be received by the standby server ie., WAL files that are needed by standby to be in sync. It keeps a track of that. If the standby goes down, the master can keep track of how much the standby lags and preserve the WAL files it requires until the standby reconnects. The WAL files are then decoded and played back on the duplicate. Basically If you have a master and some hot or archiving standbys, and you are running streaming replication between them, a replication slot is used to retain the WAL files even when the replica is offline or disconnected.
-
What is cascading replication?
Cascading replication, introduced with PostgreSQL 9.2, enables a standby server to replicate from another standby server rather than directly from the primary, meaning replication changes “cascade” down through a hierarchy of servers. This can be used to reduce load on the primary and minimize bandwidth usage between sites. Asynchronous replication mode is only supported.
-
What happens when you don’t have a primary key in Logical replication?
When you have a primary key on a column, it identifies the record easily. If you don’t have a primary key you have to tell the logical replication to consider the entire row because it won’t allow you to delete a record. How to do that? You have to run this command:
ALTER TABLE emp REPLICA IDENTITY FULL;
With this command, you inform the publication that the replica identity is the entire row.
About AWS
AWS offers 2 options for managing PostgreSQL database. RDS Postgres and Aurora compatible Postgres. Which one is better? Depends on the workload characteristics. Scaling and DR requirement and Value of Aurora specific features. And cost.
Amazon Aurora is a good choice for high-performance workloads that require low latency and high throughput. It can be up to 5 times faster than MySQL and 3 times faster than PostgreSQL. Amazon RDS can also be used for high-performance workloads, but it is not as fast as Amazon Aurora. Ultimately, your best choice will depend on your specific needs and requirements. If you need a high-performance, durable, and scalable database for mission-critical applications, then Amazon Aurora is a good choice.
On AWS, you have to first provision a virtual machine that is EC2 instance and then install and manage the database engine on it.
This database setup is referred to as a self managed database on AWS as the user for self managed database is responsible for carrying out almost all of the tasks as they would typically carry out on On-prem setup of the database. For eg: OS patching, DB installation, switch over, failover, etc.
Amazon RDS is a managed database service that provides 6 options for database engines for eg: MS SQL server, Oracle, PostgreSQL, MariaDB, MySQL, and Amazon Aurora.
Amazon Aurora is one of the RDS database engine option. It is wire compatible with MYSQL and PostgreSQL.
RDS PostgreSQL database can grow up to 64 TiB. And Aurora Postgres database can grow up to 128 TiB.
5 replicas can be set for RDS Postgres database instance. Aurora supports up to 15 read replicas.
RDS Postgres uses streaming replication. Whereas Aurora Postgres uses shared storage tier. RDS supports cross region replicas. Whereas incase of Aurora Postgres replicas need to be in the same region.
-
- How to switch the user from one user to another?
- What is happening in background when we start the database?
- What is log all data?
- Is it possible if archive mode is off? Can we set both replication logical and physical and how?
- How to check the parameters need restart or reload as you do not have configuration file access? Tell me the command to check.
- What is default value of wal level?
Conclusion

