Limited-Time Offer: Enjoy 50% Savings! Coupon code: 50OFF Use it at checkout
Skip to content

Free PostgreSQL CE 8 Silver PGCES-02 Exam Questions

Last updated: · 14 practice questions with answers and explanations

Page: 1 / 15 Total 142 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: PostgreSQL Fundamentals

Skill tested: Select PostgreSQL data types that preserve exact decimal values and support reliable arithmetic.

A billing service stores unit prices and tax rates that must remain exact when reports calculate totals. The application currently uses a floating-point column, and repeated calculations produce small rounding differences. The schema must support fixed decimal precision, and the developers want the database to reject values that exceed the intended scale rather than silently rely on binary floating-point representation. Which data type is the best fit for the monetary values?

Correct Answer: A. NUMERIC with an explicitly chosen precision and scale
Explanation:

NUMERIC (also called DECIMAL) stores decimal values with user-defined precision and scale, making it appropriate when exact decimal arithmetic is required. Specifying both lets the schema enforce the intended range and fractional scale. REAL and DOUBLE PRECISION use binary floating-point, so many decimal fractions cannot be represented exactly; a display-oriented check does not change that. INTEGER can work only with a carefully defined scaled-integer convention, but it does not directly represent the requested decimal values and requires conversion logic.

Question 2

New Single answer

Topic: PostgreSQL Fundamentals

Skill tested: Interpret PostgreSQL NULL semantics in predicates and construct correct null checks.

An analytics query filters customer records using `WHERE region 'West'`. The team expects this predicate to include customers whose region has not yet been recorded, but those rows are missing from the result. The database uses standard SQL null semantics, and the business definition says an unknown region should be retained alongside every known region except West. What should the query predicate use?

Correct Answer: D. `region IS DISTINCT FROM 'West'`
Explanation:

`IS DISTINCT FROM` treats NULL as a comparable value: NULL is distinct from the non-NULL string `'West'`, so unknown regions pass the predicate. Ordinary `` evaluates to unknown when `region` is NULL, and WHERE retains only true rows. Comparing with `NULL` using `!=` does not fix this because ordinary comparisons to NULL also yield unknown. `IS NOT NULL AND ...` explicitly excludes the rows the business wants to keep. COALESCE could be made to work with a sentinel, but the sentinel must be chosen safely and is less direct.

Question 3

New Multiple answers

Topic: Data Definition and Manipulation

Skill tested: Apply transactional DDL and identity-preserving sequence behavior during a schema migration.

A team is migrating an application table, `orders`, while preserving its existing data. It will add a generated numeric identifier, and new inserts must receive identifiers automatically. Existing rows must receive distinct, non-null values; the column must become the primary key; and a failure at any migration step must not leave only part of the schema change committed. The table is an ordinary PostgreSQL table, and concurrent application writes can be paused during the migration. Which two actions meet these requirements? Select TWO.

Correct Answer: D. Add a `bigserial` column and make it the primary key, with the migration statements in one transaction.; E. Run the migration statements in one transaction, add a `bigint` identity column, and make it the primary key.
Explanation:

A generated identity column (`GENERATED ... AS IDENTITY`) obtains values from a sequence and is populated for existing rows when added as a non-null identity column; a primary key then enforces uniqueness and non-nullness. `bigserial` is PostgreSQL's sequence-backed shorthand pattern for a bigint column, default, and owned sequence, so it can also provide generated values. Grouping the DDL in a transaction allows rollback if a later step fails. A bare nullable column cannot become a valid primary key with unfilled rows; a sequence without a default does not generate values automatically; and a constant default cannot provide distinct keys.

Question 4

New Single answer

Topic: Data Definition and Manipulation

Skill tested: Use conflict handling to make repeatable inserts respect a unique business key.

A data-import job may deliver the same external event more than once. The `event_log` table has a unique constraint on `source_event_id`; a duplicate should leave the already stored row unchanged, while new events should be inserted. The import must continue processing later rows rather than aborting when it encounters a duplicate. Which statement provides this behavior directly?

Correct Answer: D. `INSERT INTO event_log (...) VALUES (...) ON CONFLICT (source_event_id) DO NOTHING;`
Explanation:

`ON CONFLICT (source_event_id) DO NOTHING` handles a uniqueness conflict by skipping that row, allowing the statement to continue without changing the existing event. `RETURNING` only reports inserted or modified rows and does not suppress a conflict. A plain insert raises a unique-violation error, which can abort the statement or transaction. A no-op-looking `DO UPDATE` still performs an update, potentially firing triggers, changing audit fields, and creating unnecessary row versions; it does not satisfy the requirement to leave the stored row unchanged.

Question 5

New Single answer

Topic: SQL Querying and Optimization

Skill tested: Choose an index strategy that supports equality filtering and ordered range retrieval.

A service frequently runs `SELECT ... FROM measurements WHERE device_id = $1 AND measured_at >= $2 ORDER BY measured_at DESC LIMIT 100`. Each device has many timestamped rows, and the planner currently scans a large portion of the table and sorts the matching rows. The query is central to the service, writes are moderate, and the team wants one index that supports both the equality restriction and the timestamp range/order. Which index is the best starting point?

Correct Answer: C. A B-tree index on `(device_id, measured_at DESC)`
Explanation:

A multicolumn B-tree with `device_id` first supports an equality condition on the leading column, then a range scan over `measured_at`; its descending ordering can also support the requested newest-first retrieval and LIMIT. Reversing the key order is less effective when there is no constraint on the leading timestamp column. Hash indexes support equality, not the combined range and ordering needs. GIN is intended for searchable composite or document-like values, not this ordinary scalar range-and-order access pattern.

Question 6

New Multiple answers

Topic: SQL Querying and Optimization

Skill tested: Preserve unmatched rows while calculating grouped aggregates and filtering groups correctly.

A retailer needs a report listing every store, including stores with no sales, and the number of completed sales for each store. The report should include only stores with fewer than five completed sales. `stores.store_id` is a primary key, and `sales.store_id` references it; `sales.status` identifies completed sales. Store rows with no completed sales must appear with a count of zero. Which two SQL design decisions are necessary? Select TWO.

Correct Answer: A. Group by the store key and use `HAVING COUNT(sales.sale_id) < 5`.; C. Use a `LEFT JOIN` from `stores` to `sales`, placing the completed-status condition in the join condition.
Explanation:

A LEFT JOIN preserves every store. Keeping the completed-status filter in the join condition means stores with no qualifying sale still have a null-extended row. Grouping by the store key and counting a non-null sales key yields zero for such stores; HAVING then filters aggregate groups while retaining zero-count stores. An inner join removes stores without sales. Moving the sales filter to WHERE rejects null-extended rows and effectively removes those stores. `COUNT(*)` counts the preserved placeholder row as one, and omitting the status condition counts sales that are not completed.

Question 7

New Single answer

Topic: SQL Querying and Optimization

Skill tested: Read EXPLAIN ANALYZE evidence to distinguish estimate errors from execution bottlenecks.

After an application release, a query becomes slow. `EXPLAIN ANALYZE` shows a sequential scan of a large table, with estimated rows far below actual rows. The table was recently bulk-loaded, and no statistics collection has run since the load. The query filters on a selective column that already has a suitable B-tree index. The DBA wants to identify the underlying cause before changing the query or adding another index. What is the best next action?

Correct Answer: C. Run `ANALYZE` on the table, then capture and compare a new execution plan.
Explanation:

The large estimate-versus-actual row-count discrepancy following a bulk load points to stale planner statistics. `ANALYZE` refreshes those statistics so the planner can make more informed selectivity and access-path estimates; the new plan then shows whether the existing index is appropriate. Disabling sequential scans globally or permanently is a diagnostic workaround, not a sound fix, and a sequential scan can still be correct. Duplicating an equivalent index adds write and storage cost without addressing stale estimates. `work_mem` does not correct row-count statistics.

Question 8

New Multiple answers

Topic: Database Administration

Skill tested: Select a physical backup and recovery sequence that meets point-in-time recovery requirements.

A payment platform must recover a PostgreSQL cluster to a point shortly before an accidental data change. Management requires recovery to any point within the retained recovery window, not merely to the time of the latest nightly backup. The cluster can be restored onto a replacement server, and the team can retain archived transaction logs securely off-host. Which two components are required for this recovery approach? Select TWO.

Correct Answer: B. A complete, continuous sequence of archived WAL files from the base backup through the target time.; D. A valid base backup of the cluster taken before the target recovery point.
Explanation:

Point-in-time recovery uses a base backup as the starting state and replays the required continuous WAL sequence to the chosen recovery target. Both must be available and valid; a gap in required WAL prevents replay to a later point. A table-only logical dump can restore selected objects but does not provide physical cluster PITR. A replication slot is not a substitute for a base backup and does not itself archive WAL to durable storage. Copying a live WAL directory without a coordinated backup and verification does not establish a consistent recovery chain.

Question 9

New Single answer

Topic: Database Administration

Skill tested: Diagnose transaction ID wraparound risk and prioritize vacuum remediation.

Monitoring reports that a production database is approaching transaction ID wraparound protection limits. Application traffic is still active, and an overnight maintenance job has been disabled. The DBA must prevent the server from reaching forced shutdown while minimizing data loss and avoiding an unnecessary restart. Which action should be taken first?

Correct Answer: B. Run `VACUUM` on the affected databases and restore appropriate autovacuum operation.
Explanation:

VACUUM advances transaction ID horizons by freezing old tuples, helping prevent wraparound. The appropriate response is to vacuum the affected databases promptly and ensure autovacuum is functioning; PostgreSQL may impose protective restrictions if wraparound approaches. Restarting does not reset transaction IDs or solve the underlying issue. `VACUUM FULL` rewrites tables, takes stronger locks, and requires additional disk space; it is not required merely to prevent wraparound. Increasing connection capacity does not directly improve autovacuum scheduling.

Question 10

New Single answer

Topic: Advanced PostgreSQL Features

Skill tested: Implement a row-level audit trigger using transition data and trigger return semantics.

A compliance team needs an audit row whenever a row in `employee` is updated. Each audit record must capture the old and new row values, and the update must proceed normally. The audit logic should apply to every updated row, including updates issued by maintenance scripts, and it must execute in the same transaction as the change. Which design is most appropriate?

Correct Answer: B. An AFTER UPDATE FOR EACH ROW trigger that inserts OLD and NEW values into the audit table and returns NULL.
Explanation:

An AFTER UPDATE FOR EACH ROW trigger receives OLD and NEW for each affected row and can insert both versions into an audit table within the same transaction. For an AFTER row trigger, its return value is ignored, so NULL is conventional and does not cancel the update. A statement-level trigger does not provide a single OLD/NEW row pair for each changed row. Returning OLD from a BEFORE trigger would substitute the old row values for the proposed update, preventing the requested change. An AFTER trigger's return value likewise does not control whether the update occurs.

Question 11

New Single answer

Topic: Advanced PostgreSQL Features

Skill tested: Choose a PostgreSQL extension installation method compatible with managed database restrictions.

A reporting team wants to use PostgreSQL's `pg_trgm` extension to accelerate similarity searches. The database is on a managed service where server files cannot be installed by customers, but the provider supports selected contrib extensions. The team has database-owner privileges and must avoid modifying the server installation. What is the appropriate approach?

Correct Answer: C. Check that `pg_trgm` is in the provider-supported extension list, then run `CREATE EXTENSION pg_trgm` in the target database.
Explanation:

PostgreSQL extensions must be available in the server installation, and a database administrator can register an available extension in a database with `CREATE EXTENSION`. Managed providers restrict server filesystem changes but often expose a supported-extension allowlist; confirming support and creating the extension in the target database fits those constraints. Copying a shared library or restarting a managed server is not available to the customer. A schema with the same name does not install extension objects. `LOAD` loads a shared library into a session but does not create the extension's database objects or configuration.

Question 12

New Single answer

Topic: High Availability and Disaster Recovery

Skill tested: Configure streaming replication prerequisites and distinguish standby operation from automatic failover.

A company is setting up a physical standby for a PostgreSQL primary. The goal is to keep a continuously updated copy on a separate host, but operators will perform promotion manually after assessing a failure. They want to avoid losing required WAL while the standby is disconnected briefly, and they can configure WAL archiving. Which design best meets these requirements?

Correct Answer: A. Use physical streaming replication with a replication-capable connection and configure WAL archiving for the required recovery window.
Explanation:

Physical streaming replication transfers WAL to a standby capable of following the primary's physical changes. Archiving WAL provides a means to bridge periods when streaming cannot deliver required segments, assuming the archive is retained and the standby is configured to retrieve them. A replication connection and appropriate standby configuration are also required. Logical replication transfers selected logical changes and is not a physical standby promotion mechanism. A one-time directory copy is not a consistent replication setup. Synchronous commit controls commit acknowledgement behavior; it neither creates a standby nor performs automatic failover.

Question 13

New Multiple answers

Topic: High Availability and Disaster Recovery

Skill tested: Reduce replication lag by correcting WAL retention and standby recovery configuration.

A standby fell behind during a network outage and now repeatedly requests a WAL segment that the primary has already recycled. The organization has no requirement for automatic failover, but it does require the standby to catch up without rebuilding it whenever outages are shorter than the documented recovery window. Disk capacity is available for retaining additional WAL, and an archive repository is already in place. Which two changes directly address the failure? Select TWO.

Correct Answer: C. Increase the primary's WAL retention capacity, such as with an appropriately sized `wal_keep_size`.; E. Configure and verify WAL archiving, and configure the standby to retrieve missing WAL from that archive.
Explanation:

The standby cannot continue from a segment that has been recycled on the primary unless that WAL is available elsewhere. Archiving the WAL and configuring standby recovery to fetch it provides durable retrieval; increasing `wal_keep_size` can retain more recent WAL on the primary for shorter interruptions. Capacity should be sized to the stated outage window and monitored. `max_connections` and `synchronous_commit` do not restore missing WAL. A primary index does not recreate deleted WAL and is unrelated to segment availability.

Question 14

New Single answer

Topic: Security

Skill tested: Apply least-privilege role grants and separate login identity from object ownership.

A data-warehouse analyst needs read-only access to tables in schema `reporting`, including tables created there in the future. Analysts must not create objects, modify data, or own the schema. The organization wants to grant permissions through a reusable group role and keep individual login credentials separate from privileges. Which approach is most appropriate?

Correct Answer: A. Create a NOLOGIN reader role, grant schema USAGE and SELECT on existing tables, configure default SELECT privileges for future tables, and grant the role to analyst login roles.
Explanation:

A NOLOGIN group role separates reusable privileges from individual authentication identities. Schema USAGE permits name resolution, while SELECT on existing tables grants read access; default privileges ensure tables created later receive the intended grant (configured by the role that creates them). Granting the group role to individual login roles preserves separate credentials. Ownership is broader than read access and cannot be reduced simply by revoking common DML privileges. CONNECT alone does not grant table access. CREATE is unnecessary, and a shared login weakens accountability.