icon Join with us for Oracle DBA Training Live Session ENROLL NOW

PostgreSQL DBA Interview Questions

Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
PostgreSQL
  • 30 Jan, 2025
  • 0 Comments
  • 112 Mins Read

PostgreSQL DBA Interview Questions

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. What are some important background processes in postgres?

    PostgreSQL has several important background processes that ensure smooth database operation:

    1. Checkpointer – Flushes dirty pages from shared buffers to disk at regular intervals to reduce write overhead.
    2. WAL Writer – Writes transaction logs (WAL – Write-Ahead Logging) to ensure data durability and crash recovery.
    3. Autovacuum Daemon – Cleans up dead tuples to prevent table bloat and optimize performance.
    4. Background Writer – Helps reduce I/O spikes by pre-writing dirty pages to disk before checkpoints occur.
    5. Archiver – Handles WAL file archiving when continuous archiving is enabled.
    6. Stats Collector – Gathers database statistics for query optimization and performance monitoring.
    7. Logical Replication Launcher – Manages logical replication workers for data synchronization between databases.
    8. WAL Receiver/Sender – Handles streaming replication between primary and standby servers.

    These background processes enhance performance, data integrity, and high availability in PostgreSQL.

  6. What are the memory components in postgres?

    PostgreSQL has several important memory components that optimize performance and manage database operations efficiently:

    1. Shared Buffers – Caches frequently accessed data pages to reduce disk I/O.
    2. Work Memory – Allocated per query for sorting and hashing operations.
    3. Maintenance Work Memory – Used for maintenance tasks like vacuuming and indexing.
    4. WAL Buffers – Temporary storage for Write-Ahead Logging (WAL) before writing to disk.
    5. Effective Cache Size – An estimate of how much OS cache PostgreSQL can use for query planning.
    6. Temp Buffers – Session-local buffers used for temporary tables.
    7. 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.

  7. 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.

  8. 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:

    1. WAL Buffers are Full – If the WAL buffer fills up, WAL Writer flushes data to WAL segments.
    2. Timeout Occurs – It writes at regular intervals (wal_writer_delay, default 200ms) to prevent data loss.
    3. Transaction Commit – WAL entries are flushed when a transaction commits to ensure durability.
    4. Checkpoints Trigger – During a checkpoint, WAL data is written and synced to disk for consistency.
  9.  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.

  10. What is restore_command?

    restore_command in PostgreSQL is a configuration setting that specifies the command used to retrieve archived WAL (Write-Ahead Log) files during recovery or replication.

  11. 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.

  12. What is recovery_target_time?

    recovery_target_time is a configuration parameter in PostgreSQL that specifies the exact point in time to which the database should be recovered during point-in-time recovery.

  13. What is pg_dumpall?

    pg_dumpall is a PostgreSQL utility that backs up the entire database cluster—including all databases, roles, and global objects—into a single dump file.

  14. 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 by wal_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.

  15. 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:
    CREATE TABLESPACE my_tablespace LOCATION '/data/my_tablespace';
  16. What is checkpoint? When checkpoint happens in postgres?
  17. Which parameters controls the behaviour of BGWriter?

    The Background Writer (bgwriter) behavior in PostgreSQL is controlled by the following parameters:

    1. bgwriter_delay → Defines the interval (in ms) between background writer runs (default 200ms).
    2. bgwriter_lru_maxpages → Sets the maximum number of dirty pages written to disk per bgwriter cycle.
    3. bgwriter_lru_multiplier → Determines how aggressively bgwriter writes pages based on buffer usage (default 2.0).
  18. 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.

  19. 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

  20. What is continuous archiving?

    Method of archiving WAL files continuously
    Essential for PITR capability

  21. What is autovacuum in PostgreSQL?

    Automated process that removes dead tuples and updates statistics
    Essential for maintaining database performance

  22. 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.

  23. 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.

  24. How do you take a hot backup?

    To take a hot backup in PostgreSQL using pg_basebackup while the database is running:

    1. Enable ARCHIVE_MODE:
      Set archive_mode = on and configure archive_command in postgresql.conf, then restart PostgreSQL.
    2. Run pg_basebackup:
      Use pg_basebackup to take a backup:

      pg_basebackup -h localhost -D /path/to/backup -U replicator -P --wal-method=stream
  25. How do you create a user and assign privileges in PostgreSQL?

    To create a user in PostgreSQL, use the CREATE USER command:

    CREATE USER username WITH PASSWORD 'password';
    

    To assign privileges, you can grant specific permissions like SELECT, INSERT, UPDATE, etc., using the GRANT command. 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;
  26. How do you take a full database backup using **pg_dump**?

    To take a full database backup using pg_dump, use the following command:

    pg_dump -U username -F c -b -v -f /path/to/backupfile.dbname.tar dbname
  27. How do you manage users and roles in PostgreSQL?

    In PostgreSQL, manage users and roles using SQL commands: create users with CREATE ROLE username WITH LOGIN PASSWORD 'password';, assign roles with GRANT role TO user;, and set permissions with GRANT SELECT ON table TO user;. Modify roles with ALTER ROLE, remove with DROP ROLE, and manage privileges using REVOKE. Use pg_roles view to monitor roles and permissions.

  28. How authentication happens in postgres?
    1. Password-Based Authentication – Uses MD5, SCRAM-SHA-256, or plain passwords for user verification.
    2. Trust – Allows connections without authentication (used for local, trusted environments).
    3. Peer Authentication – Uses OS user credentials to match PostgreSQL roles (Unix/Linux only).
    4. Ident Authentication – Relies on an external Ident server to verify the user.
    5. Kerberos, LDAP, PAM, and SSPI – Supports enterprise authentication mechanisms for secure login.
    6. Certificate-Based Authentication – Uses SSL/TLS certificates for secure connections.
  29. 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.

  30. What is pg_stat_statements?

    pg_stat_statements is a PostgreSQL extension that records execution statistics of SQL queries for performance monitoring and tuning.

  31. What are connection limits?

    Connection limits in PostgreSQL define the maximum number of concurrent connections allowed per database or user, preventing resource exhaustion.

  32. What is primary_conninfo?

    primary_conninfo in PostgreSQL is a configuration parameter in recovery.conf or postgresql.conf that specifies the connection details for a standby server to stream WAL data from the primary server.

  33. What is pg_stat_activity?

    pg_stat_activity is a PostgreSQL system view that shows information about currently active database connections.

  34. What is recovery.conf?

    In PostgreSQL <12, the recovery configuration is managed using the recovery.conf file.
    In PostgreSQL ≥12, recovery is managed using recovery.signal for recovery-related settings and standby.signal to enable replication.

  35. 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.

  36. What is application_name in replication?

    application_name in PostgreSQL replication identifies a replica or client connection in the primary server’s pg_stat_replication view for monitoring and management.

  37. What are wait events?

    Wait events in PostgreSQL indicate the resource or condition a process is waiting for, helping diagnose performance bottlenecks.

  38. What is pg_audit?

    pg_audit is a PostgreSQL extension that provides detailed logging of database activities for security and compliance auditing.

  39. What is pg_dumpall?

    pg_dumpall is a PostgreSQL utility that backs up the entire database cluster—including all databases, roles, and global objects—into a single dump file.

  40. What is archive_command?

    archive_command in PostgreSQL is a configuration setting that specifies the command used to archive WAL (Write-Ahead Log) files to a safe location for point-in-time recovery (PITR).

  41. How do you handle bloated tables and indexes?

    To handle bloated tables and indexes in PostgreSQL, use VACUUM to reclaim space from deleted rows. For severe bloat, run VACUUM FULL to compact the table and reclaim disk space. For bloated indexes, use REINDEX to rebuild them. Regular autovacuum helps manage bloat over time. Monitoring tools like pg_stat_user_tables and pg_stat_all_indexes can help identify and manage bloat efficiently.

  42. What are the different types of backups in PostgreSQL?
    • Logical Backup – Uses tools like pg_dump and pg_dumpall to export data in SQL or other formats for selective restoration.
    • Physical Backup – Copies database files directly using pg_basebackup or 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.
  43. What is this wal_level parameter , different values of wal_level?

    The wal_level parameter 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
    1. minimal → Generates only enough WAL for crash recovery (no replication or PITR).
    2. replica (default) → Supports streaming replication and PITR, recording changes at the row level.
    3. logical → Includes additional details for logical replication and decoding (used for logical replication tools).
     
  44. 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.

  45. What is log_min_duration_statement?

    log_min_duration_statement is a PostgreSQL setting that logs SQL statements taking longer than a specified time, helping in performance monitoring.

  46. 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.

  47. 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.

  48. 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.

  49. What is pg_stat_bgwriter?

    pg_stat_bgwriter is a PostgreSQL view that provides statistics on the background writer process, helping monitor checkpoint activity and buffer management.

  50. 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.

  51. 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.

  52. What is pg_stat_database?

    pg_stat_bgwriter is a PostgreSQL view that provides statistics on the background writer process, helping monitor checkpoint activity and buffer management.

  53. 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.

  54. How do you list all databases and tables?

    To list all databases in PostgreSQL, use the following command:

    \l   -- or  \list
    

    To list all tables in the current database, use:

    \dt
    
  55. 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.

  56. What is the difference between **VACUUM**, **ANALYZE**, and **VACUUM FULL**?

    In PostgreSQL, VACUUM reclaims storage by cleaning up dead tuples without locking tables, improving performance over time. ANALYZE collects statistics on table contents to help the query planner optimize queries. VACUUM FULL, unlike regular VACUUM, reclaims space more aggressively by compacting tables and indexes, but it requires an exclusive lock on the table, making it more disruptive. Use VACUUM regularly, ANALYZE for query optimization, and VACUUM FULL for severe bloat or space reclamation.

  57. 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.

  58. What is track_io_timing?

    track_io_timing is a PostgreSQL setting that enables tracking of I/O operation times for query performance analysis.

  59. 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.

  60. How do you perform a failover in PostgreSQL?

    To perform a failover in PostgreSQL, promote the standby to primary using pg_ctl promote or a trigger file. Update application connections to the new primary. Reconfigure the old primary as a standby if needed. Tools like Patroni, Repmgr, or Pgpool-II can automate failover for high availability.

  61. 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.

  62. What is pgcrypto?

    pgcrypto is a PostgreSQL extension that provides cryptographic functions for encryption, hashing, and data security.

  63. How do you change a user’s password?

    To change a user’s password in PostgreSQL, use the following command:

    ALTER USER username WITH PASSWORD 'new_password';
  64. Explain Logical Replication vs Physical Replication

    Logical Replication in PostgreSQL replicates specific tables or databases by streaming changes at the SQL level, allowing selective data replication, cross-version replication, and flexible replication setups. In contrast, Physical Replication copies the entire database at the disk level using WAL files, providing exact copies of the database for high availability, but without table-level granularity. Logical replication is more flexible, while physical replication is faster and simpler for full database replication.

  65. 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.

  66.  Describe the purpose of the pg_isready command in PostgreSQL.What is initial fork?

    The pg_isready command 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.

    pg_isready -h localhost -p 5432 -U postgres
  67. How do you enable SSL in PostgreSQL?

    To enable SSL in PostgreSQL, modify postgresql.conf by setting ssl = on and specifying certificate and key files (ssl_cert_file and ssl_key_file). Update pg_hba.conf to allow SSL connections using hostssl. Restart the PostgreSQL service for changes to take effect. Ensure the server has valid SSL certificates to establish secure connections.

  68. Explain the role of **WAL (Write-Ahead Logging)** in PostgreSQL.

    Write-Ahead Logging (WAL) in PostgreSQL ensures data durability and crash recovery by recording changes to a log before applying them to the data files. WAL allows PostgreSQL to recover from crashes by replaying logs and supports Point-In-Time Recovery (PITR) and replication. By minimizing disk writes and enabling efficient backups, WAL enhances database reliability, consistency, and performance

  69. 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.

  70. What is log_checkpoints?

    log_checkpoints is a PostgreSQL setting that logs checkpoint activity, helping monitor database write performance and recovery behavior.

  71. Explain Row-Level Security (RLS) in PostgreSQL.

    Row-Level Security (RLS) in PostgreSQL controls access to individual rows in a table based on user roles. It is enabled with ALTER TABLE table_name ENABLE ROW LEVEL SECURITY; and policies are created using CREATE POLICY to define conditions for row access. RLS ensures that users see only the rows they are authorized to access, enhancing data security and isolation.

  72.  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.

  73. What is pg_stat_user_tables?

    pg_stat_user_tables is a PostgreSQL system view that provides statistics on user-defined tables, including tuples read, inserted, updated, and deleted.

  74. 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.

  75. What is pg_locks?

    pg_locks is a PostgreSQL system view that displays information about locks held by active transactions, helping in diagnosing concurrency issues.

  76. 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 BLCKSZ parameter.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 custom BLCKSZ value.

  77. What is pgvector?

    pgvector is a PostgreSQL extension for storing and querying high-dimensional vector embeddings, enabling efficient similarity search.

  78. 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.

  79. What is pg_cron?

    pg_cron is a PostgreSQL extension that enables scheduled execution of SQL commands using the database’s internal cron-based job scheduler.

  80. How do you detect and fix database corruption?

    To detect database corruption in PostgreSQL, check logs for errors and use tools like pg_check or pg_dump to identify issues. The pg_catalog views can also help spot inconsistencies. To fix corruption, restore from a recent backup, use pg_resetwal if needed, or rebuild corrupted indexes and tables. Regular backups and CHECKSUMS help prevent and recover from corruption efficiently.

  81. 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.

  82. What is pg_stat_monitor?

    pg_stat_monitor is a PostgreSQL extension that provides enhanced query performance metrics and statistics for advanced database monitoring and analysis.

  83. 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.

  84. What are the different **index types** in PostgreSQL?
    PostgreSQL supports several index types to optimize query performance:
    1. B-Tree Index – Default and most commonly used, ideal for range and equality queries.
    2. Hash Index – Optimized for exact matches, but less commonly used due to WAL limitations (before PostgreSQL 11).
    3. GIN (Generalized Inverted Index) – Best for full-text search and JSONB queries.
    4. GiST (Generalized Search Tree) – Used for geospatial, full-text, and complex data types.
    5. BRIN (Block Range INdex) – Efficient for large tables with sequentially correlated data.
    6. SP-GiST (Space-Partitioned GiST) – Supports hierarchical and non-balanced tree structures.

     

  85. What is the significance of search_path in postgres?

    The search_path in 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 in search_path, from left to right, until it finds a match.

    By default, it includes the public schema, 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.

  86. 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.

  87. What is pg_partman?

    pg_partman is a PostgreSQL extension that automates the creation and management of table partitioning for improved performance and data organization.

  88. 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.

  89. What is parallel query?
    • Multiple workers executing parts of query
    • Controlled by max_parallel_workers parameter
  90. 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 (now pg_xact in 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 (now pg_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.
     
  91.  What is ctid?

    ctid is 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 ctid changes when a row is updated or moved (e.g., by VACUUM FULL), it is not a reliable primary key but is useful for efficient row lookups, indexing, and low-level operations like DELETE optimizations.

  92. What is pg_bouncer?

    PgBouncer is a lightweight connection pooler for PostgreSQL that reduces overhead by managing database connections efficiently.

  93. 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

  94. What is oid?

    Every row in postgres will have a object identifier called oid.

  95. 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.

  96. 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 uses relfilenode to map a relation (pg_class.relfilenode) to its actual storage file in the base/ directory. If VACUUM FULL or REINDEX is performed, the relfilenode can change, but the oid remains the same.
  97. 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.

  98. 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 VIEW to update data.

  99. 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.

  100. 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

  101. 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.

  102. 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.

  103. What is shared_buffers?

    shared_buffers is a PostgreSQL configuration parameter that determines the amount of memory allocated for caching data blocks to reduce disk I/O.

  104. 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.

  105. What is pg_upgrade?

    pg_upgrade is a PostgreSQL tool that upgrades databases to a new major version quickly without dumping and restoring data.

  106. 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.

  107.  What is the default port in postgres?

    Default is 5432.

  108. What is event trigger?

    An event trigger in PostgreSQL is a special trigger that fires in response to DDL events like CREATE, ALTER, or DROP.

  109. 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.

  110. What is difference between pg_cancel_backend vs pg_terminate_backend?
    1. 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.
    2. 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_backend when you want to stop a long-running query without disconnecting the session.
    • Use pg_terminate_backend when you need to forcefully disconnect a session, such as in case of blocking transactions or resource-heavy queries.
  111. What is the use of pgbench utility?

    pgbench is 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

  112. 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.

  113. What is table sampling?

    Table sampling in PostgreSQL allows querying a random subset of rows from a table using methods like TABLESAMPLE SYSTEM or TABLESAMPLE BERNOULLI.

  114. 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.

  115. 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.

  116. How to handle connection issues?

    Handle connection issues in PostgreSQL by checking network settings, authentication configurations (pg_hba.conf), server logs, and resource limits.

  117. Which utility is used to upgrade postgres cluster?

    pgbouncer is used for connection pooling

  118. 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.

  119. How to identify slow queries?

    Identify slow queries in PostgreSQL using EXPLAIN ANALYZE, pg_stat_statements, and log_min_duration_statement.

  120. What are the popular tools for managing backup and recovery in postgres?

    edb bart , barman etc

  121. How to handle disk full?

    VACUUM FULL
    Remove unused indexes
    Archive old data

     

  122. What are the different types of replication in PostgreSQL?

    PostgreSQL supports Streaming Replication (WAL-based real-time standby), Logical Replication (table-level replication via PUBLICATION/SUBSCRIPTION), Physical Replication (disk-level data copy), Synchronous Replication (zero data loss), and Asynchronous Replication (better performance with minimal data loss risk). Tools like pglogical, Slony-I, and Bucardo offer additional replication options.

  123. Describe the purpose of the pg_rewind command in PostgreSQL.

    The pg_rewind command 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_rewind efficiently rewinds the diverged instance by copying only the changed data, making it faster and reducing downtime.

    pg_rewind --target-pgdata=/var/lib/postgresql/data --source-server="host=new_primary user=postgres"
    
  124. What is an extension in postgres? Which extensions you have used ?

    pg_stat_statements

    pg_track_settings

    pg_profile

  125. How do you set up Streaming Replication?

    To set up Streaming Replication in PostgreSQL, enable WAL logging on the primary server (wal_level = replica, max_wal_senders = 3), create a replication user, and allow standby connections. On the standby server, use pg_basebackup to copy data, create standby.signal (PostgreSQL 12+), and configure primary_conninfo in postgresql.conf. Restart the standby server to start replication.

  126. 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):

    SELECT pg_cancel_backend(pid);

    This stops the running query but keeps the session active.

    Terminate a Session (forcefully kill the session):

    SELECT pg_terminate_backend(pid);
  127. How you monitor long running queries in postgres?

    we can use pg_stat_activities to track .

  128. How to fix high CPU usage?

    Fix high CPU usage in PostgreSQL by optimizing queries, indexing properly, tuning configuration settings, and monitoring pg_stat_statements for expensive queries.

  129. 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 WITH clause, CTEs can be referenced multiple times within a query. They are especially useful for recursive queries and breaking down complex logic.

  130. What is the role of pg_stat_replication?

    pg_stat_replication is 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;
  131. 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:

    SELECT * FROM pg_stat_bgwriter;
  132. 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.
  133. 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.

  134. 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.

    CREATE TABLE data (info JSON, info_b JSONB);
    
  135. 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.

  136. How do you create a new database in PostgreSQL?

    To create a new database, use the SQL command:
    sqlCopy code
    CREATE DATABASE dbname;

  137. How to handle replication lag?

    Handle replication lag in PostgreSQL by tuning wal_sender_timeout, optimizing network performance, increasing max_wal_size, and monitoring pg_stat_replication.

  138. 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.

  139. 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.

  140. How to fix database bloat?

    Fix database bloat in PostgreSQL by running VACUUM (FULL), ANALYZE, using autovacuum, and implementing table partitioning where necessary.

  141. 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.

  142. 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 (without LOGIN). Privileges define what actions a role can perform, such as SELECT, INSERT, UPDATE, DELETE, CREATE, CONNECT, and EXECUTE. Roles are granted privileges using the GRANT command and revoked using REVOKE. This role-based access control (RBAC) system ensures secure and efficient permission management.

  143. What is the latest version of postgres in market?

    Postgres 15.

  144. 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.

  145. How to handle connection pooling?

    Handle connection pooling in PostgreSQL using tools like PgBouncer or Pgpool-II to manage and optimize database connections efficiently.

  146. How can i check the version of postgres?

    cat PG_VERSION file.

    or select pg_version();

  147.  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.

  148. 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.

  149. 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.

  150. 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

  151. 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.

  152. 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.

  153. 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 .

  154. 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.

  155. 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.

  156. What are the different datatypes in postgres?

    Boolean
    char,vchar,
    int,float(n)
    uuid
    date

  157. Explain the concept of parallel queries in PostgreSQL.

    Parallel queries use multiple worker processes to execute parts of a query concurrently, improving query performance.

  158. How to improve checkpoint performance?

    Improve checkpoint performance in PostgreSQL by tuning checkpoint_timeout, max_wal_size, checkpoint_completion_target, and monitoring pg_stat_bgwriter.

  159. 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.

  160. 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.

  161. What is the full form of MVCC?

    The full form of MVCC is Multi-version Concurrency Control.

  162. 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.

  163. 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.

  164. What is random page cost?

    random_page_cost is a PostgreSQL parameter that defines the cost of fetching a random disk page during query execution. It influences the query planner’s decision when choosing between index scans and sequential scans. A higher value (default: 4.0) makes sequential scans more favorable, while a lower value encourages index scans. Adjusting this setting based on storage type (HDD vs. SSD) can improve query performance.

  165. 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)
    synchronous_commit
    (controls commit behavior)
    primary_conninfo (connects standby to primary
    hot_standby (enables read queries on standby)

  166.  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.

  167. 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.

  168. Explain the concept of logical replication in PostgreSQL.

    Logical replication replicates data changes using a publish-subscribe mechanism at the row level.

  169. 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.

  170. 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.

  171. 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;

  172. What are the default databases created after setting up postgres cluster?

    postgres=# select datname from pg_database;
    datname
    ———–
    postgres
    template1
    template0

  173. 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:

    SET temp_tablespaces = 'my_temp_tablespace';
  174. 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.

  175. 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.

  176. 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.

  177. What tools do you use for monitoring PostgreSQL performance?

    To monitor PostgreSQL performance, use pg_stat_activity to track active queries and long-running transactions, and pg_stat_statements to analyze query execution statistics. Tools like EXPLAIN ANALYZE help optimize queries, while pgAdmin provides a GUI for real-time monitoring. For advanced monitoring, tools like Prometheus with PostgreSQL Exporter, Grafana, and PGBouncer can be used to track performance metrics, connections, and query execution times.

  178. What are the tablespaces created by default after installing postgres cluster?

    After installing a PostgreSQL cluster, two default tablespaces are created:

    1. pg_default – Stores user-defined tables, indexes, and other database objects by default.
    2. 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.

  179. What is analyze?

    In PostgreSQL, ANALYZE collects statistics on table data distribution to help the query planner generate efficient execution plans.

  180. How do you check the current connections and terminate a session?

    To check current connections in PostgreSQL, query pg_stat_activity:

    SELECT pid, usename, datname, client_addr, application_name, state FROM pg_stat_activity;
    

    To terminate a specific session, use:

    SELECT pg_terminate_backend(pid);
    

    For immediate termination, use:

    SELECT pg_cancel_backend(pid);
  181. What are common causes of deadlocks, and how do you resolve them?

    Deadlocks in PostgreSQL occur when two or more transactions hold locks that the other transactions need, causing a cyclic wait. Common causes include transactions updating rows in different orders, long-running transactions holding locks for too long, and foreign key constraints with cascading updates/deletes. To resolve deadlocks, ensure transactions access resources in a consistent order, keep transactions short, and use appropriate indexing to reduce lock contention. Monitoring pg_stat_activity and using deadlock_timeout settings can help detect and troubleshoot deadlocks efficiently.

  182. How do you handle bloated tables and indexes?

    To handle bloated tables and indexes in PostgreSQL, use the VACUUM and ANALYZE commands to reclaim storage and update statistics. For severe bloat, run VACUUM FULL, which locks the table but compacts it effectively. Use REINDEX to rebuild bloated indexes. The pg_stat_user_tables and pg_stat_all_indexes views help identify bloat. For automated maintenance, enable autovacuum or use tools like pg_repack to reclaim space without locking tables.

  183. 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).

  184. 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;
  185. What is the use of EXPLAIN ANALYZE?

    EXPLAIN ANALYZE in PostgreSQL is used to analyze and optimize query performance. It provides a detailed execution plan by showing how the database processes the query, including cost estimates, row estimates, index usage, join methods, and execution time. This helps identify inefficiencies such as sequential scans instead of index scans, slow joins, or misestimated row counts. By using EXPLAIN ANALYZE, developers can fine-tune queries by adding indexes, rewriting queries, or adjusting PostgreSQL configuration settings to improve performance.

  186. 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_basebackup or by copying the data directory. Enable WAL archiving by setting archive_mode = on and archive_command. To restore, stop the database, replace data files with the base backup, and configure recovery settings in recovery.conf (or postgresql.auto.conf in newer versions) with restore_command and recovery_target_time. Restart PostgreSQL, and it will replay WAL logs up to the specified point, ensuring precise data recovery.

  187. What is the purpose of **pg_hba.conf**?

    The pg_hba.conf (PostgreSQL Host-Based Authentication) file controls client authentication in PostgreSQL. It defines which users can connect, from which hosts, and what authentication methods are required. Each entry specifies a connection type (local, host, hostssl, hostnossl), database, user, client IP address, and authentication method (e.g., md5, trust, peer, scram-sha-256). PostgreSQL checks this file when a client attempts to connect, ensuring secure access based on predefined rules.

  188. How do you optimize query performance in PostgreSQL?

    To optimize query performance in PostgreSQL, use EXPLAIN ANALYZE to analyze execution plans and identify bottlenecks. Create appropriate indexes (B-tree, GIN, BRIN) based on query patterns. Use VACUUM and ANALYZE to update statistics and prevent bloat. Optimize queries with proper JOINs, WHERE filters, and indexing on frequently searched columns. Avoid **SELECT ***; instead, fetch only required columns. Use partitioning for large tables and connection pooling for handling multiple queries efficiently. Tune PostgreSQL settings like work_mem, shared_buffers, and parallel_execution for better performance.

  189. How do you restore a corrupted database?

    To restore a corrupted Oracle database, first identify the issue using V$DATABASE_BLOCK_CORRUPTION and alert logs. If datafiles are missing or corrupt, restore them using RMAN: RESTORE DATABASE; RECOVER DATABASE;. For control file corruption, restore from backup or recreate it. If redo logs are corrupted, clear or drop them. Block corruption can be fixed with RMAN BLOCKRECOVER or DBMS_REPAIR. If the entire database is affected, perform a full RMAN restore and recovery. Regular backups, ARCHIVELOG mode, and proactive monitoring help prevent future corruption.

  190. What is the purpose of the pg_basebackup command?

    The pg_basebackup command is used to take a physical backup of a PostgreSQL database, including data files and WAL segments. It is commonly used for full database backups, replication setup, and Point-In-Time Recovery (PITR). This tool ensures fast, consistent backups without requiring database downtime.

     

  191.  Why is postgres OPEN SOURCE DATABASE?

    Postgres Database is worlds most advanced open source database because it is community driven. Multiple companies and Individual contribute to the project and drive innovation. Developed and maintained by Pistgresql community. Postgres database performance wise , scalability wise, and extensibility wise on TOP among other RDBMS.

     

  192. What are the features of EDB POSTGRES ADVANCED SERVER?

    So the features are all the same , whatever features are available on Postgresql. The same features are also available on EDB POSTGRES ADVANCED server. It is just that EDB POSTGRES ADVANCE SERVER is not an open source.Features:
    Portable: It is ANSI compliant. It supports various Operating system Windows, Linux, MaC , and other maj or unix platforms.
    Reliable: It is ACID compliant. It also supports transactions logging which is also known as WRITE AHEAD LOGGING in Postgres.
    Scalable: Postgres makes sure that concurrency is maintained. It also supports table partitioning. Tablespace can be created. It also supports Parallel query features.
    Secure: Postgres is secure. For client connection , all the IP addresses must be defined in HBA CONF File. HBA stands for HOST BASED ACCESS Control.
    Recovery & Availability: It supports HOT BACKUP, PG_BASEBACKUP, and Point in time recovery.

     

  193. What features does postgres provide under Security?

    User Profile: User profiles can help in password and login management.
    Data redaction: Data reduction can redact sensitive data from selected users.
    Auditing: It also enhance auditing features which can help with Enterprise level auditing and compliance requirement.
    Row level security: It can help in implementing VPD which can help in hiding selected rows from a selected users.
    Injection Attack Guard: It also protects from SQL Injection, you can implement SQL protect.

     

  194. 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.

  195. What is ACID?

    ACID transactions help to ensure the reliability and consistency of a database.
    PostgreSQL ensures the ACID properties through a combination of mechanisms, such as the write- ahead log (WAL), multi- version concurrency control (MVCC), and various database constraints. These mechani sms work together to provide atomicity, consistency, isolation, and durability in PostgreSQL. ACID transa ctions ensure that database transactions are reliable and consistent, even in the face of errors, power fail ures, or other problems. The acronym ACID stands for atomicity, consistency, isolation, and durability. Atomicity : If the database went down prior to a commit of a transaction, all the successful queries in the tr ansactions should roll back. Consistency: It keeps the database consistent. Isolation: Isolation ensures that concurrent transactions do not interfere with each other. Durability: Durability ensures that the changes made by a committed transaction are permanent and will s urvive any subsequent failures.

  196. 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.

  197. What is WRITE AHEAD LOGGING?

    WAL helps in implementing durability in ACID compliant databases. WAL can be used to perform a point in time recovery using WAL REPLAY. WAL can also be used to implement streaming replication and logical replication. If you want an automatic recovery after an abrupt shutdown of a database cluster, set WAL level to MINIMAL. For Autorecovery, hot backups, PITR support and streaming replication set WAL level to REPLICA. Additionally if you want to set up logical replication, set WAL_LEVEL to logical. Logical Level writes the highest amount of logging contents to WAL files. WAL_LEVEL is set to REPLICA by default. The WAL_WRITER background process performs WAL Buffer flush at each commit and this behavior is controlled by the FSYNC Parameter. You can set your cluster in non-durable mode by turning off FSYNC parameter which means WAL buffers are not flushed to disk at each commit.—WAL_LEVEL, FSYNC, WAL_BUFFER, MAX_WAL_SIZE, CHECKPOINT_TIMEOUT, etc are parameters all related to WRITE AHEAD LOG SETTINGS. We all know PostgreSQL is ACID compliant database. So when we write data, server must ensure durability. To ensure durability, we have transaction logging which is also known as WRITE AHEAD LOGGING. All changes are written to the shared buffer as well as the WAL buffer area. At each commit, modified data in the WAL buffer are flushed to the WAL segments or the transaction log area or WAL files. This is done by the WAL writer process. When the WAL segment is full, it switches to a new WAL segment and archiver process will send those WAL files to archive log files.

     

  198. 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.

  199. What does Postgresql.conf file store?

    It is the server parameter file for PostgreSQL server.

  200. What is PG_HBA.conf file?

    The IP address authentication is done by using PG_HBA.CONF File.

  201. What is PG_IDENT.conf file?

    It is used to perform operating system authentication.

  202. 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.

  203. What is Database cluster in PostgreSQL?

    A database cluster is a collection of databases managed by a single server instance.

  204. What is Database cluster in PostgreSQL?

    A database cluster is a collection of databases managed by a single server instance.

  205. 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.

  206. 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.

  207. 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.

  208. 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.

  209. 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:

    1. In the Tablespace, I specify on the create database statement.

    2. In the default tablespace defined in the PostgreSQL configuration file.

    3. 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.

  210. 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.

  211. 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.

  212. 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.

    1. EDB_DYNATUNE parameter is used to specify a limit on the resources that can be used by database server.

    2. EDB_DYNATUNE_PROFILE can be set to OLTP or reporting or mixed based on the type of workload expected on the database.

  213. 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.

  214. 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.

  215. 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.

  216. 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.

  217. 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.

  218. 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.

  219. 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.

  220. 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.

  221. 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.

  222. 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.

  223. 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.

  224. 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:

    text
    \c edb
    ANALYZE;

  225. 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.

    text
    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)

  226. What are the 2 tablespaces created by default? And can we move objects (table) from one tablespace to another tablespace?
    1. PG_GLOBAL tablespace: It is used for Shared System catalogs.

    2. PG_default tablespace: It is the default tablespace of the template 1 and template 0 databases.

    Command:

    sql
    ALTER TABLE ALL IN TABLESPACE tbs1 SET TABLESPACE pg_global;

  227. 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.

  228. 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.

    1. Vacuum full will lock the table, vacuum will not.

    2. 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.

  229. 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.

  230. 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.

  231. 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:

    sql
    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.

  232. What is PG_VISIBILITY MAP used for?

    The Visibility Map (VM) is a special auxiliary data structure in PostgreSQL that is associated with each table. It is stored in a separate file alongside the table’s data file (with a _vm suffix). Its primary purpose is to track which pages (blocks) in a table contain only “live” (visible) tuples and which pages contain “dead” (obsolete) tuples.

    Key Uses of the Visibility Map:

    1. Speeding up VACUUM:

    • During a VACUUM operation, PostgreSQL can skip pages that are marked as “all-visible” in the visibility map. This dramatically reduces the amount of work VACUUM needs to do, especially on large tables where most pages haven’t changed.

    • Without the visibility map, VACUUM would have to scan every single page of a table.

    2. Enabling Index-Only Scans:

    • An Index-Only Scan is a query optimization where PostgreSQL can retrieve all required data directly from the index without accessing the table’s heap (data pages). This is only possible if the visibility map confirms that all tuples on the relevant pages are visible to all transactions.

    • If a page is marked as “all-visible” in the visibility map, PostgreSQL knows it doesn’t need to check the heap for visibility, making index-only scans much faster.

    3. Tracking All-Visible Pages:

    • Each bit in the visibility map corresponds to one page in the table’s heap file.

    • If the bit is set (1), it means all tuples on that page are visible to all current and future transactions (i.e., no dead tuples, and no tuples that are invisible due to uncommitted or aborted transactions).

    • If the bit is not set (0), it means the page may contain dead tuples or tuples that are not yet visible to all transactions.

    4. Updated by VACUUM:

    • The visibility map is not updated automatically by regular DML operations (INSERT, UPDATE, DELETE). It is updated by the VACUUM process (including autovacuum) after it has cleaned up dead tuples on a page and determined that all remaining tuples are visible to all transactions.

    Summary Table:

    Aspect Description
    What it is A bitmap file associated with each table, tracking page visibility status
    File suffix _vm (e.g., 12345_vm)
    Primary purpose Track which pages contain only all-visible tuples
    Used by VACUUM, Index-Only Scans
    Updated by VACUUM / Autovacuum
    Benefit Faster VACUUM, enables Index-Only Scans, reduces I/O

    In Simple Terms:

    The Visibility Map is like a cheat sheet for PostgreSQL that says: “This page has only live, visible data — you don’t need to check it again for cleanup or visibility purposes.” This saves a massive amount of I/O and CPU time during maintenance and query execution.

  233. 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:

    sql
    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:

    text
    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:

    sql
    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:

    text
    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:

    sql
    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:

    text
    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.

    sql
    VACUUM emp;
    VACUUM FULL emp;

  234. 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.

  235. 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

  236. What is Visibility map & Free space map?

    Visibility Map (VM):
    The Visibility Map is a special auxiliary data structure associated with each table. It tracks which pages (blocks) in a table contain only “live” (visible) tuples and which pages contain “dead” (obsolete) tuples. It is stored in a separate file alongside the table’s data file (with a _vm suffix). Its primary purposes are:

    • Speeding up VACUUM: PostgreSQL can skip pages marked as “all-visible” during VACUUM, dramatically reducing work on large tables.

    • Enabling Index-Only Scans: If a page is marked as “all-visible,” PostgreSQL knows it doesn’t need to check the heap for visibility, making index-only scans much faster.

    Each bit in the visibility map corresponds to one page in the table’s heap file. If the bit is set (1), all tuples on that page are visible to all current and future transactions. If not set (0), the page may contain dead tuples or tuples not yet visible. The visibility map is updated by the VACUUM process (including autovacuum), not by regular DML operations.

    Free Space Map (FSM):
    The Free Space Map is another auxiliary data structure associated with each table. It tracks the amount of free space available on each page of a table’s heap file. It is stored in a separate file (with a _fsm suffix). Its primary purpose is:

    • Finding space for new tuples: When PostgreSQL needs to insert a new row (tuple), it uses the Free Space Map to quickly locate a page that has enough free space to accommodate the new tuple, rather than scanning the entire table.

    • Reducing I/O: By maintaining this map, PostgreSQL avoids unnecessary page reads when looking for free space.

    The Free Space Map is updated by VACUUM and also by regular INSERT/UPDATE operations as they consume free space on pages.

     

  237. What is max_connection? If Max connection has already achieved What action will you take?

    PostgreSQL has a maximum of 115 connections to the database, 15 connections are reserved to the super user to maintain the integrity of the PostgreSQL database, and 100 PostgreSQL connections are reserved for system applications. Max_connection property in PostgreSQL determines concurrent connection to the database server. Before increasing the size of the connection, you need to scale up system deployment. Every PostgreSQL connection uses system RAM to maintain connection; if we have more connections, we require more RAM to maintain them.

    If Max connection has already achieved, Will I increase the max_connection value? Definitely No!! It will impact our entire system. At first I will check all the connections, are they active, Idle, idle in the transaction (Idle in transaction means there is no input received from the end-user, so it is waiting for the state.) If I see lot of Idle connections, then we can kill those Idle sessions to free up our compute resources.

    If there are all active sessions from the application end, all are concurrently accessing the database, Then they will be consuming lot of CPUs and I/O subsystem will be burdened. More the number of connection, more issues with the memory allotted to the server. So on our host where PostgreSQL is running, we have limited memory so if we increase max_connection then we can run out of our memory. There is mathematical calculation–

    For eg Max_Connection should be lesser than the maximum number of cores which are there on your operating system. And then Parallel I/O limit which is divided by the Session busy Ratio multiplied average parallelism.

    Parallel I/O limit = Number of concurrent I/O request your storage subsystem can handle.

    Session_Busy_Ratio = Fraction of time that the connection is actively executing SQL statement.

    Average_parallelism = average number of backend processes working on a single query.

    Note: Without proper detailed analysis, you can not increase Max_connection. When you increase, remember Max connection depends on Shared buffer and kernel Shmmax on the Operating system side. And there is a TOOL called PG_TUNE for Parameters settings. You can put the required information for eg: DB version, OS type, DB Type, Total memory, No. of CPUs, etc and generate. It will suggest you to use the Shared buffer parameter settings and for other parameters also it will suggest the values that we can take.

     

  238. What is connection pooling?

    Connection pooling refers to the method of creating a pool of connections and caching those connections so that it can be reused again.

    PostgreSQL has a postmaster process, which spawns new processes for each new connection to the database. This process takes up around 2 to 3 MB memory which happens every time you create a connection to the database. Without connection pooling, for each connection, the postmaster process will have to spawn a new process at the backend using 2 to 3 MB memory and this creates a problem if the number of connections are too high (typically seen in mission critical applications). Higher the number of connections, more is the memory consumed for creating these connections.

    With Connection pooling, whenever there is a request from the front-end application to create a connection to the database, a connection is created from the pool. After the session or transaction is completed, connection is given back to the pool. PostgreSQL does provide two great tools to solve the problem of wasting resources for every connection to the database.

    PGPOOL-2

    PGBOUNCER

    Both of these tools can be placed on the application server or the database server. Disadvantages are: For authentication, you will have to rely on the Connection Pooler that may or may not be acceptable. And also it is an Additional component in your infrastructure that you have to maintain and manage that might add some cost to your infrastructure. Both of these tools have been developed by the community keeping in mind the PostgreSQL architecture and are specifically designed for PostgreSQL database. While pgbouncer provides only connection pooling, pgpool provides connection pooling, load balancing, high availability and replication. It literally distribute the read only queries load on master and slave. Either of these tools can be used based on the amount of traffic you expect and the overall architecture of your database. Let’s see how pgbouncer helps in improving your database performance by minimizing the time required to make a database connection.

    As explained earlier, Pgbouncer is a lightweight connection pooler for PostgreSQL that dramatically reduces the processing time and resources for maintaining many client connections to one or more databases. Pgbouncer supports three types of pooling when rotating connections: Session pooling / Transaction pooling / Statement pooling

    Session pooling: A server connection is assigned to the client application for the life of the client connection. PgBouncer releases the server connection back into the pool once the client application disconnects. This is the default method.

    Transaction pooling: A server connection is assigned to the client application for the duration of a transaction. When PgBouncer detects the completion of the transaction, it releases the server connection back into the pool. Transaction mode is good for performance.

    Statement pooling: A server connection is assigned to the client application for each statement. When the statement completes, the server connection is returned into the pool. Multi-statement transactions are not permitted for this mode.

    Apart from the pool_size, pool_mode and connection details, you can also set other parameters in pgbouncer configuration file. Some other useful parameters are as follows:

    • min_pool_size – This parameter specifies the minimum number of server connections in pool. At any time, when using pgbouncer, you will see this many number of connections on your server either idle or active.

    • reserve_pool_size – Additional connections to be used in case of issues.

    • server_idle_timeout (seconds) – All server connections will be removed after being idle for this many seconds.

    • idle_transaction_timeout (seconds) – Close connections which are in ‘idle in transaction’ state for this many second.

    • max_client_conn – Total number of clients that can connect.

    Connection pooler does really good when the concurrent users are between the range of 400 to 500 users. It does well with the small numbers of connections expected.

    Note: Pg_bouncer doesn’t provide load balancing and High availability. If you just need connection pooling then go with PG BOUNCER. It is easy to set up and maintain.

    OR

    pgbouncer is a PostgreSQL connection pooler. Any target application can be connected to pgbouncer as if it were a PostgreSQL server, and pgbouncer will create a connection to the actual server, or it will reuse one of its existing connections.

    The aim of pgbouncer is to lower the performance impact of opening new connections to PostgreSQL.

    Pgbouncer supports several types of pooling when rotating connections:

    Session pooling

    Most polite method. When client connects, a server connection will be assigned to it for the whole duration the client stays connected. When the client disconnects, the server connection will be put back into the pool. This is the default method.

    Transaction pooling

    A server connection is assigned to client only during a transaction. When PgBouncer notices that transaction is over, the server connection will be put back into the pool.

    Statement pooling

    Most aggressive method. The server connection will be put back into pool immediately after a query completes. Multi-statement transactions are disallowed in this mode as they would break.

    OR

    Benchmarks have proven that standard PostgreSQL performs well alone up to 350 concurrent transactions per second. However, if you expect more transaction then it is important to maintain a connection pooler. In this case, PGBouncer will help improve the performance of your system. The basic Idea of Pgbouncer is to save connection related cost.

    When a user tries to connect to a database, it usually means burning a couple of 100 KB and also the actual connection process could be time consuming. In the background the postmaster process performs a Fork system call which creates an address space, a file descriptor and a copy of the memory segments as of the postmaster process and once the client disconnects the child process gets terminated.

    How to configure? Run the pgbouncer rpm and install it. Once installed then edit pgbouncer.ini file and put the database name for connection pooling.

    Database SECTION:

    text
    demodb = host=10.10.18.1 port=5444 dbname=demodb

    Pgbouncer SECTION:

    text
    auth_type = trust/md5
    admin_users = admin
    vi /etc/pgbouncer/userlist.txt --> "admin" "password"
    pgbouncer -d /etc/pgbouncer/pgbouncer.ini

     

  239. What is Watch Dog?

    If you are using multiple instances of PG POOL, you can use the WATCH DOG Feature. It will check the PG Pool nodes and provides a failover capability using the WATCH DOG.

     

  240. What is Forking in PostgreSQL?

    It is a process of creating the child process that looks similar to the parent process that created it. The child process is known as “Forking”.

    Both parent and child process has the same code of segments with a different address space.

    The Forking Process (a) child process has a different process ID.

    As per the PostgreSQL architecture, the postmaster is the first background process that will starts when the cluster is started. Based on the postmaster ID other background utility processes details are given below.

    • BG writer,

    • Check pointer,

    • WAL writer,

    • Archive WAL writer,

    • Logger,

    • Statistical collector,

    • Autovacuum launcher

    All of these processes are created or ‘Forking’ by the postmaster as child processes, if you see below each child process have a different ID, but with the same parent ID (a) postmaster ID.

     

  241. What is PG_repack?

    Pg_repack utility works exactly the same way as Vacuum Full to remove dead tuples and bloating. The only thing is to use PG_REPACK you need to first explicitly download it and use it as an extension.

    Advantages: Release storage from database or tables to DISK. It doesn’t put a lock on the table while removing the dead tuple or bloating.

    You can use “yum install pg_repack12” –> connect to psql –> set shared_preload_libraries = ‘pg_repack’; –> Restart the database –> Connect to the database where you want to run the PG_REPACK utility –> \c dvrental –> CREATE EXTENSION pg_repack;

    Once extension is created then you can run pg_repack utility.

    For eg: /pg_repack –dry-run -d dvrental –table emp (It will do the dry run)

    OR

    –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.

     

  242. What is a password file in PostgreSQL database?

    Password file is available in Home directory of PostgreSQL database. Or you can create one. Password file name is pgpass. You can create using “vi .pgpass” –> Inside the editor –> #format is as below

    text
    #hostname:port:database:username:password
    localhost:5432:postgres:postgres:adil@123

    wq!

    Change the permission –> chmod -R 0600 /home/enterprisedb/.pgpass

     

  243. When do we use PG_RESTORE and PSQL Utility in backups?

    While restoring data, we can use PSQL utility or PG_RESTORE Utility. If backup taken using “pg_dump or pg_dumpall” with PLAIN TEXT FORMAT then PSQL Utility will be useful. And If Backup taken using “pg_dump or pg_dumpall” with CUSTOM (FC), TAR (FT) or DIRECTORY (FD) formats in such cases we can use PG_RESTORE Utility for restoration.

     

  244. What is Logical backup and physical backup?

    Logical backup can be taken using PG_DUMP and PG_DUMP ALL utility.

    Physical backup can be taken like – File system level backup using “tar -cvf backup.tar /postgres/data” -> In order to get a useable backup, a database should be shutdown.

    OR

    “./pg_dump -Ft -p 5444 -U postgres -f /tmp/dvrental.sql -d dvrental”.

    File system level backup can be taken ONLINE and OFFLINE.

    PG_BASEBACKUP is the latest way and you can use this utility while the database is ONLINE. It will automatically put the database in Begin backup and end backup mode. The backup can be used for Point in time recovery.

    For PG_BASEBACKUP – Continuous archiving mode is mandatory.

    Requirements are:

    • Wal_level = Replica

    • Archive mode = ON

    • Archive command must be set.

    • Max_WAL_SENDER = 3

    • WAL_KEEP_SIZE = 512

     

  245. What is PG_BASEBACKUP utility used for?

    PG_BASEBACKUP is used to take base and WAL backups while the database is ONLINE. It will automatically put the database in Begin backup and end backup mode. The backup can be used for Point in time recovery. It will complete backup of your data directory. PG base backup creates a copy of the database cluster’s file. So it is not possible to backup individual database or object. Plain and TAR formats are supported.

    For PG_BASEBACKUP – Continuous archiving mode is mandatory.

    Requirements are:

    • Wal_level = Replica

    • Archive mode = ON

    • Archive command must be set.

    • Max_WAL_SENDER = 3

    • WAL_KEEP_SIZE = 512

    • WAL_KEEP_SEGMENTS = 100

     

  246. How to perform Point in Time Recovery?
    • Stop the server. Take a File system level backup if possible. Clean the data directory.

    • Copy data cluster files and folders from backup location to the data directory. Use “cp -rp” to preserve privileges.

    • Configure recovery settings in postgresql.conf file. Create recovery.signal file in the data directory.

    • Start the server using Pg_ctl utility. Check error log for any issue. Recovery.Signal file is removed automatically after recovery.

     

  247. What is the concept of Reverse engineering?

    Reverse engineering is basically — Reading the changes that is happening on the WAL FILES and the changes are reversed apply on the standby PostgreSQL server so whatever changes are happening in the Primary PostgreSQL cluster via the WAL FILES they are getting transferred to the STANDBY Side. So we have to put the standby server in a recovery mode.

     

  248. What is streaming/physical replication?

    In Streaming replication, WAL files don’t get transferred to Remote side. In Streaming replication there is a background process which starts on Primary “WAL SENDER” and a background process starts on Standby server “WAL RECEIVER” as well. The background process on the standby server contacts the primary server directly. And it picks up the changes available from primary server PG_WAL file folder (OLD NAME: PG_XLOG folder.) And then hand over the Log files to another background process on the standby server and then that process will apply those logs to Standby server.

    Parameters that are required to be SET:

    • WAL_LEVEL = Replica

    • ARCHIVE_MODE = ON

    • MAX_WAL_SENDER = 5

    • WAL_KEEP_SEGMENTS = 100

    12.13.4 (standby IP) –checkpoint=fast -D backup directory

    IN PG_HBA CONF FILE replication server ip address entry needs to be present.

    text
    host replication postgres 172.23.32.3/32 trust

    And on the standby side: RECOVERY.CONF settings need to be set:

    text
    STANDBY_MODE = ON
    Primary_conninfo = 'host=172.23.21.4 (primary server IP) port=5444 user=postgres trust'

     

  249. What is HOT STANDBY & Warm standby?

    In Hot standby, the standby database will be in recovery mode and as well as user will be able to perform read operation. Not write. The settings which need to be set:

    PRIMARY SIDE: WAL_LEVEL = replica and on standby side: HOT_STANDBY = ON.

    A warm standby is something where the database is in recovery mode and it is applying all the data which it is receiving from the master server. No write or read is allowed. The database will be not open for any request. It will be in continuous recovery mode.

     

  250. How does Logical replication works/ architecture?

    Logical replication / Transactional replication (same)

    So basically you have your primary database and standby database. You decided to go for Logical replication where you want to replicate few tables from Primary database to standby database. So you create a publisher on Primary and subscriber on standby server. Subscriber is the receiver and publisher the sender of data. As soon as Once subscriber connects publisher, replication slot is created. That is logical replication slot. The WAL files which gets generated in primary will not be understood by the standby server as it is not a byte to byte replication. That’s where decoding happens. There is WAL sender process in Primary. It sends the decoded data in the form of logical messages to the standby server. There is a process called Logical replication launcher which spawns a logical replication worker whose job is to receive the Logical messages and ensure that it gets replicated. you can do replication on Table level, Row level, column level etc

    OR

    In Physical replication, it will copy the complete cluster to the replica server. And in Logical replication, you can even copy a table to the replication server. First PostgreSQL has to decode logically the records from the WAL file and make SQL statements. Then the SQL statements are streamed over the network to the standby server. Finally the statements are applied to the tables in the standby server in the correct transactional order. In logical replication, we have 2 entities a Publisher and Subscriber. A publisher is a node that represents certain group of tables also called publication. Then to receive the changes from that particular group of tables a subscriber can sign up by creating a subscription. Another point in favor of the logical replication is that the amount of data that has to be replicated. For physical replication, versions have to be same. In logical replication, versions are not important as the data transfer happen at the level of SQL and not the low level of bytes. We can configure the subscriber to have different data structures as long as the SQL commands can be executed. Therefore we can use logical replication to perform migrations and upgrades.

    In Logical replication, there is no master and standby. There is publisher and subscriber. And we can set multiple architecture based on our needs for instance we could have one subscriber that is pulling data from 2 machines or more and it aggregates the data. Or we can have one publisher who is broadcasting data to one or more subscriber each with its own set of tables. Logical replication works on the level of individual tables or subsets of tables.

    OR

    In Logical replication, it follows a PUBLISH and SUBSCRIBE Model so you have a publisher instance and subscriber instance. On the publisher instance, you can create publication which will publish multiple tables and on the subscriber side we have to create subscription that will connect to publication so you want to replicate those tables to the subscriber end. So once you create a subscription, a subscription slot will be created in the publisher instance. And a WAL sender process and logical replication worker will be spawned. So the WAL sender process will take the WAL, decode it, filter whatever is needed for whatever tables are being replicated, and send it to the subscriber.

     

  251. What are the steps that we follow in LOGICAL Replication?

    First we have to create the publication and subscription so when you do that it will automatically create a replication slot on the Publisher side. And then the next phase is Table synchronization phase. In this phase, COPY Command does the work so whatever existing data you have in the publisher table it will get copied to the subscriber and once that is done all the real time changes will be sent by the WAL SENDER PROCESS so it will decode the changes from the WAL and send those changes to the subscriber. And Logical replication worker in the subscriber end will apply the changes in the subscriber tables.

     

  252. What are the Logical replication criteria?
    • Table name should be same in publisher and subscriber.

    • Column Order doesn’t matter.

    • Column type should be same. Different types are allowed if they can be converted implicitly.

     

  253. What is log_statement parameter?

    It is a useful parameter in PostgreSQL used for logging error in logfiles, database warning message and SQL queries.

     

  254. What is the most common issue with streaming replication going out of sync?

    Issues can be with the below points:

    • Sending WAL

    • WAL receiver

    • High load on primary

    • High load on replica

    • Network issues between primary and replica.

     

  255. What are the methods that PostgreSQL supports for logging server messages?
    • stderr (standard error log)

    • CSVLOG

    • SYSLOG

    The default is to log to stderr only.

     

  256. What is PG_STAT_ACTIVITY view used for?

    Pg_stat_activity is used for finding blocked queries, Long running queries, etc. so basically it will show information related to the current activity going on in the database. If any problem occurs, you can use this view for investigation.

     

  257. What is pg_stat_statements view used for? How to install pg_stat_statements extension?

    pg_stat_statements is a built-in PostgreSQL extension that keeps track of SQL statements executed by the database server. It records details about query execution counts, total execution time and I/O related info. By capturing this information, database administrators can identify bottlenecks and optimize queries for better overall performance.

    You can install the pg_stat_statements extension.

    Steps:

    1st – you have to install the contrib extension on your server.

    2nd – Under postgresql.conf file, there is a parameter “SHARED_PRELOAD_LIBRARIES = ‘pg_stat_statements'”. Add it. And restart the server.

    3rd – Connect to psql and Create extension pg_stat_statements;

    Note: You can also bring changes to the parameter below as per the business requirement.

    text
    pg_stat_statements.max = 5000 ---> This parameter will ensure it will keep those many statements.
    pg_stat_statements.track = top ---> TOP/ALL/None (Top - it will track all the statement coming from clients. ALL- It will track all the top level nested and sort queries.)

     

  258. What is DRITA stands for and usage?

    DRITA stands for Dynamic Runtime Instrumentation Tools Architecture. It allows to determine the wait events which are affecting Performance of the database. DRITA is one of the performance tool available in EDB advanced server. You can load some data and take the snapshot with the help of this DRITA tool. You can multiple snapshots and do comparison. Please set the timed_statistics parameter to TRUE. By default it is false. And it is the prerequisite of DRITA functionality on PostgreSQL database.

     

  259. What is the use of TIMED_STATISTICS parameter?

    In order to collect timing information on your server, please set the timed_statistics parameter to TRUE. By default it is false. And it is the pre-requisite of DRITA functionality on PostgreSQL database.

     

  260. What is pg_bench in PostgreSQL?

    Pgbench by default creates 16MB database. so we can scale it with option scaling to 25. To create database 25 times bigger than the default size (16*25 = 400 MB) size database.

    Pg_bench is a program for running benchmark tests on PostgreSQL database. It calculates the average transaction rate (Transaction per second). It helps administrator to prepare the system for their application needs. You can load data into the database and find out whether your database is capable enough to handle that load. So basically it helps in measuring performance find out how much load a server can take.

    For eg: create testdb -> go to bin path -> ./pg_bench -i testdb -> When you initialise pg_bench then 4 tables will be created “pgbench_history”, “pgbench_tellers”, “pgbench_accounts”, “pgbench_branches”. While running pgbench tool, you can also mention options like scaling factor, no. of clients, no. of transactions, etc and check how the database behave.

     

  261. What is TPC-B in pg_bench?

    Transaction Processing Performance Council Benchmark C. So we can say in simple terms, TPC-B in pg_bench measures throughput in terms of how many transactions per second a system can perform.

     

  262. What is PG_BACKREST?

    Pg_backrest is an open source backup tool which is an enhancement of pg_basebackup tool. In Pg_base backup, we can take full backup of the PostgreSQL cluster. In Pg_backrest, we can take FULL BACKUP and Differential incremental backup. All we have to do to is to set the below parameters for pg_backrest functionality:

    text
    Alter system set wal_level = 'replica'
    alter system set archive_mode = ON
    alter system set archive_command = 'pgbackrest --stanza=mystanza archive-push %p';
    alter system set max_wal_senders = 10
    alter system set hot_standby = ON;

    How to implement Pg_backrest?

    • install pg_backrest

    • Create a repository for pg_backrest

    • Edit a pg_backrest configuration file in /etc/pg_backrest/pgbackrest.conf and put backup repository location (repo1-path=/var/lib/pg_backrest, repo1-retention-full=2) (pg1-path=data path, pg1-port=5444)

    • Configure archiving in the postgresql.conf file: archive_mode = on, archive_command = ‘pgbackrest –stanza=my_stanza archive-push %p’ and restart the server

    • create stanza: ./pgbackrest stanza-create –stanza=my_stanza –log-level-console=info

    • command for backup: pgbackrest backup –stanza=my_stanza –log-level-console=info

    • For restoration command: pgbackrest restore –stanza=my_stanza –log-level-console=info

     

  263. What is stanza?

    A stanza is the configuration for a PostgreSQL database cluster that defines where it is located, how it will be backed up, archiving options, etc. Most db servers will only have one PostgreSQL database cluster and therefore one stanza, whereas backup servers will have a stanza for every database cluster that needs to be backed up.

     

  264. What is the use of DELTA in restoration using pgbackrest?

    With the help of the delta option, pgBackRest can automatically decide which files in the database cluster need to be restored, by comparing the backup to the current state of the database cluster. This can significantly speed up the restore process by only restoring files that have changed.

     

  265. Explain the concept of RTO and RPO?

    To ensure that you always have a recent backup of your database, it’s important to create a backup schedule. The frequency of your backups will depend on your requirements for RPO (recovery point objectives) and RTO (recovery time objectives).

    RTO: It specify the amount of time to recover from a disaster or it is the maximum database downtime an organization can handle or how quickly the organization can regain access to the database after an outage.

    RPO: It is about how much data you can afford to lose – after recovery from a disruptive event. RPO helps determine how much data an organization can tolerate losing during an unforeseen event. It is dependent on backup and how valid the backup is.

     

  266. How pg_basebackup works in background?

    Low level steps are as follows:

    => Issue pg_start_backup command

    => Switch the current WAL segment file.

    => Do checkpoint. (Depends on – checkpoint value. It can be immediate or default checkpoint time)

    => Create a backup label file – This file contains the contents of the backup_label file which includes checkpoint Location, timeline info, backup source (Primary/Standby). During Restoration from base backup, PostgreSQL looks for backup_label file and starts recovering from given checkpoint location.

    => Issue the pg_stop_backup command.

     

  267. Which parameters to look for while using pg_basebackup?

    Following parameters should be used in pgbasebackup command:

    • -F: Selects the format for the output. Only plain (default) and tar format is available.

    • -Xs: Stream write-ahead log data while the backup is being taken. This will ensure that your backup is up-to-date.

    • -z: Enables gzip compression of tar file output.

    • -c: Sets checkpoint mode to fast (immediate) or spread (pgbasebackup will wait until the next checkpoint timeout).

     

  268. Why tune Shared Buffers in PostgreSQL?

    Tuning the shared buffers parameter can bring about several benefits:

    Reduced Disk I/O: shared buffers helps reduce the need to read data from disk. When data is in memory, it can be accessed much faster than when it has to be retrieved from disk or OS cache.

    Query Response Time: Faster data retrieval translates into quicker query response times.

     

  269. Why not over-allocate shared buffers?

    While more RAM sounds good, it doesn’t always lead to better performance. It’s important to leave enough free RAM for the operating system and other database tasks like hashing, sorting, vacuuming, or indexing to work well. If shared buffers take up too much memory, other processes might not get the memory they need, leading to poorer performance. You might also run into errors due to lack of memory. Generally it is advised to keep the value of shared buffers at 25% of the available memory.

     

  270. What is work_mem?

    In PostgreSQL, work_mem sets the maximum amount of memory to be used by a query operation like sorting and hashing before writing to temporary disk. By default, work_mem is set to 4MB. It can be set inside postgresql.conf file or at session level.

     

  271. When to tune work_mem in PostgreSQL?

    Tuning work_mem can improve performance in a number of scenarios:

    • When you are running a query that involves a large amount of sorting or hashing.

    • When there are large amounts of temporary files being created on disk.

    • When you see external merge disk operation inside EXPLAIN ANALYZE plan.

    Tuning work_mem can lead to faster query execution and efficient resource management. However, it is important to be cautious when tuning work_mem to prevent excessive memory usage. Regular monitoring and adjustment of work_mem based on query patterns and resource availability are crucial for maintaining optimal database performance.

     

  272. How to make autovacuum aggressive?

    Enable more autovacuum workers, increase cost limit for each worker, reduce sleep time between autovacuum runs and make autovacuum worker threads less interruptable by setting cost delay. (This can cost higher I/O and CPU consumption).

     

  273. How to tune PostgreSQL for memory?

    shared_buffers:

    The shared_buffers parameter determines how much memory is dedicated to the server for caching data. The default value for this parameter, which is set in postgresql.conf, is:

    text
    #shared_buffers = 128MB

    The value should be set to 15% to 25% of the machine’s total RAM. For example: if your machine’s RAM size is 32 GB, then the recommended value for shared_buffers is 8 GB. Please note that the database server needs to be restarted after this change.

    work_mem (integer)

    The work_mem parameter basically provides the amount of memory to be used by internal sort operations and hash tables before writing to temporary disk files. Sort operations are used for order by, distinct, and merge join operations. Hash tables are used in hash joins and hash based aggregation. The default value for this parameter, which is set in postgresql.conf, is:

    text
    #work_mem = 4MB

    Setting the correct value of work_mem parameter can result in less disk-swapping, and therefore far quicker queries.

    We can use the formula below to calculate the optimal work_mem value for the database server:

    text
    Total RAM * 0.25 / max connections

    maintenance_work_mem (integer)

    The maintenance_work_mem parameter basically provides the maximum amount of memory to be used by maintenance operations like vacuum, create index, and alter table add foreign key operations. The default value for this parameter, which is set in postgresql.conf, is:

    text
    #maintenance_work_mem = 64MB

    It’s recommended to set this value higher than work_mem; this can improve performance for vacuuming. In general it should be:

    text
    Total RAM * 0.05

    effective_cache_size (integer)

    The effective_cache_size parameter estimates how much memory is available for disk caching by the operating system and within the database itself. The PostgreSQL query planner decides whether it’s fixed in RAM or not. Index scans are most likely to be used against higher values; otherwise, sequential scans will be used if the value is low. Recommendations are to set Effective_cache_size at 50% of the machine’s total RAM.

     

  274. What is REPMGR?

    Repmgr (Replication Manager) is an open source tool used for managing the replication and failover of PostgreSQL clusters. It was introduced in 9.0 version of postgresql.
    We have similar tools like REPMGR for eg- patroni, Pacemaker, PAF and there is one more tool developed by citus might be its pg_autofailover.

     

  275. 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.

  276. 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.

  277. 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).

  278. How is query cost is calculated?

    Cost = number of pages * seq_page_cost (parameter) + number of rows in a table * Cpu_tuple_cost (parameter).

  279. Can we disable autovacuum for a particular table?

    Yes we can. For eg:

    sql
    ALTER TABLE emp SET (autovacuum_enabled = false);
  280. 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.

  281. 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.

  282. 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.

  283. 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:

    sql
    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.

  284. What is heap table?

    In PostgreSQL, data is stored in what is called a heap table. This is the default storage method where data is arranged row-by-row, similar to a spreadsheet .

    Key characteristics include:

    • Organization: Tables are organized into pages (usually 8KB each), with each page holding pointers to the rows .

    • Optimization: Heap tables are optimized for transactional queries (OLTP), using indexes to quickly locate specific rows for reads, updates, or deletes .

    • Limitation: They perform poorly for full table scans when data cannot be found via an index, as every row must be read individually .

     

  285. How to switch the user from one user to another?

    You can switch users in PostgreSQL using several methods:

    Using SET ROLE (within a session):

    sql
    SET ROLE your_username;

    This changes the current user identifier for permission checking. You can check the current user with SELECT user;. To switch back, use \c or RESET ROLE.

    Using SET SESSION AUTHORIZATION (for superusers):

    sql
    SET SESSION AUTHORIZATION 'username';

    This sets both the session user and current user. Only superusers can change the session user; otherwise, you can only set it to the authenticated user name .

    From the command line:

    bash
    psql -U username -d database_name

    This logs you in directly as the specified user.

     

  286. What is happening in background when we start the database?

    When PostgreSQL starts, the postmaster process launches several essential background processes :

    • Checkpointer: Flushes dirty pages from shared memory to disk at regular intervals to maintain consistency and reduce crash recovery time .

    • Background Writer: Continuously scans shared buffers and writes dirty buffers to disk proactively, reducing I/O spikes during checkpoints .

    • WAL Writer: Flushes Write-Ahead Log buffers to disk regularly, ensuring transactional changes are safely stored for crash recovery .

    • Autovacuum Launcher: Initiates background workers to perform vacuum operations, cleaning up dead tuples to prevent table bloat .

    • Stats Collector (prior to PostgreSQL 14): Gathered statistics about database activity. In PostgreSQL 14+, this is handled via shared memory .

     

  287. What is log all data?

    There is no single parameter called “log all data” in PostgreSQL. However, you can control what gets logged using various parameters:

    • log_statement: Controls which SQL statements are logged (none, ddl, mod, all).

    • log_statement_stats: Outputs performance statistics of each query to the server log. Disabled by default .

    • log_parser_stats, log_planner_stats, log_executor_stats: Output per-module statistics for each query .

    • log_min_duration_statement: Logs any statement running longer than the specified time.

    To log all SQL statements, set log_statement = 'all'.

     

  288. Is it possible if archive mode is off? Can we set both replication logical and physical and how?

    Archive mode off: Yes, it’s possible to have archive_mode = off. This is actually required if you want to use wal_level = minimal for minimal WAL logging. To use minimal WAL, you must set archive_mode = off and max_wal_senders = 0.

    Both logical and physical replication: Yes, you can configure both. The key requirement is setting wal_level to logical.

    • Physical replication works with wal_level = replica or logical.

    • Logical replication requires wal_level = logical at minimum.

    So setting wal_level = logical supports both physical streaming replication (using wal_level = replica behavior) and logical replication. You configure physical replication with max_wal_senders > 0 and logical replication with max_replication_slots for logical slots.

     

  289. How to check the parameters need restart or reload as you do not have configuration file access? Tell me the command to check.

    Use the pg_settings system view to check which parameters require a restart:

    sql
    SELECT name, setting, short_desc, reset_val 
    FROM pg_settings 
    WHERE pending_restart IS true;

    This shows parameters that have been changed but require a server restart to take effect .

    To list all parameters that require restart (context = ‘postmaster’):

    sql
    SELECT name FROM pg_settings WHERE context = 'postmaster';

    Examples of parameters requiring restart include: shared_buffers, max_connections, wal_level, archive_mode, port, listen_addresses, etc. .

     

  290. What is default value of wal level?

    The default value of wal_level is replica. This is the standard setting that supports:

    • Streaming replication

    • Point-in-time recovery (PITR)

    • Hot standby

    To enable logical replication, you must explicitly set wal_level = logical. To use minimal logging (which disables archiving and replication), you can set wal_level = minimal.

    Conclusion

    PostgreSQL DBA plays a crucial role in managing, optimizing, and securing databases to ensure high availability and performance. Key aspects include monitoring system views (pg_stat_statements, pg_stat_activity), handling replication (pg_stat_replication, pg_wal), optimizing queries with indexing and EXPLAIN ANALYZE, and troubleshooting issues like connection problems, high CPU usage, and lock contention. Regular maintenance tasks like VACUUM, ANALYZE, and REINDEX help prevent bloat and corruption. Using tools like PgBouncer, Patroni, and pg_cron enhances performance, scalability, and automation. Mastering these concepts ensures a robust and efficient PostgreSQL database environment. 🚀

    For more insights, visit our YouTube channel where we regularly post tutorials and technical deep-dives: www.youtube.com/@learnomate.

    Let’s connect on LinkedIn! Follow me for more tech content and career tips: Ankush Thavali.

    If you want to read more about different technologies, check out our blog posts here: Learnomate Blog. Happy learning!

    Regards🙌

    Tech Team

    LEARNOMATE

 

 

lets talk - learnomate helpdesk

Book a Free Demo

lets talk - learnomate helpdesk

Book a Free Demo