Skip to main content

Senior — SQ001–SQ080

IDQuestionExpected answerReasoningCommon wrong answerFollow-upRelated chapter
SQ001A query became slow with no code change. What do you investigate?Workload/data distribution, stats/plan change, locks/waits, cache/I/O, bloat, parameters, concurrent load, checkpoints, deployment/config/provider changes.SQL text is only one input to runtime behavior.“The database needs a bigger instance.”Which evidence first?74,160 — Performance/Incidents
SQ002How do you prioritize query optimization work?Use workload contribution: total time, frequency, p95/p99, resource/I/O/WAL/lock impact and business SLO; then inspect representative plans.Optimizing rare slow queries may yield little system benefit.“Sort by mean execution time only.”How does pg_stat_statements help?105 — pg_stat_statements
SQ003A query has an index but chooses Seq Scan. Is that a problem?Not necessarily; planner may estimate many rows, small table, cheap sequential I/O, poor correlation, incompatible predicate, or lower total cost.Index presence is not an obligation.“Force the index.”How test planner estimate?69,70 — Planner/EXPLAIN
SQ004Estimate is 10 rows, actual is 1M. What next?Find first large estimate divergence; inspect stats/skew/correlation/joins/functions/parameters; ANALYZE or extended stats/query/model fixes; remeasure plan.Downstream bad join choices often originate earlier.“Increase work_mem.”Which extended stats type?73 — Query Statistics
SQ005How do you review a proposed index?Map exact query/operator/order, selectivity/cardinality, key order/includes/predicate, plan benefit, size/write/WAL/HOT/vacuum cost, overlap with existing indexes.Index design is workload economics.“Does it cover WHERE columns?”When prefer partial index?57 — Advanced Index Design
SQ006When would you remove an index?After proving redundancy/low value against real workload and constraints, considering rare critical queries, reset windows, replicas, and rollback plan.Unused-stat counters alone are insufficient.“idx_scan=0 means drop immediately.”How detect overlap?57,107 — Indexes/Stats Views
SQ007How do you troubleshoot high CPU?Identify top active/fingerprint workload, plan row volume/loops/expressions/JIT/parallelism, deploy/data changes; distinguish CPU from wait; shed offending load safely.CPU saturation is usually workload, not one magic config.“Raise max_connections.”What if all queries are tiny but calls explode?160 — Incident Debugging
SQ008How do you troubleshoot high I/O latency?Check buffer reads/temp spills/checkpoints/vacuum/backups/WAL/storage metrics; identify high-I/O queries and cache churn; correlate with provider limits.Database and storage workload interact.“Increase shared_buffers to RAM size.”What does pg_stat_io add?108,138 — Monitoring/Storage
SQ009How do you troubleshoot connection exhaustion?Inspect pool/app replica counts, session states, leaks/long queries/idle transactions, max/reserved capacity; restore headroom and fix admission/pooling.More connections can worsen overload.“Increase max_connections immediately.”What pool metric matters besides count?91,160 — Connections/Incidents
SQ010How do you size a connection pool?From database sustainable concurrency, transaction latency, number of app instances, workload class, reserved admin/worker capacity, and queue SLO; validate under load.Request concurrency is not DB connection requirement.“Pool size = max_connections per service instance.”What happens during autoscaling?91 — Connection Management
SQ011What changes under transaction pooling?Session state may not persist across transactions: temp tables, session advisory locks, LISTEN, prepared/session SET assumptions need review.Client logical session no longer maps to one server session.“Only connection setup gets faster.”How use tenant context safely?91,96 — Connections/RLS
SQ012How do you design a race-safe inventory reservation?Prefer atomic conditional UPDATE for simple decrement; for multi-row decisions use deterministic locks/serializable; unique idempotency; transaction around business effect.Correctness belongs at DB concurrency boundary.“SELECT quantity then UPDATE.”How reserve multiple SKUs without deadlock?67 — Concurrency Patterns
SQ013How do you design seat booking?Unique (event,seat) for discrete seats or exclusion range for interval resources; insert/constraint arbitrates race; idempotency for retries; short holds/payments outside DB transaction.Constraint makes concurrency invariant explicit.“Check availability then insert.”How handle expiring holds?67, Project 4
SQ014How do you prevent duplicate payments on retry?Persist idempotency key and payment state/business effect atomically; callbacks also dedupe; reconcile ambiguous external outcomes.Network failures can make response unknown after success.“Client should never retry POST.”Where does outbox fit?151, Project 5
SQ015How do you design a double-entry ledger?Immutable journal + balanced entries, exact amounts/currency, idempotent posting, transaction-level invariant, reconciliation, restricted mutation.Balance alone loses audit trail.“Store only account balance.”How enforce journal balance?Project 5, 192
SQ016How do you handle external side effects with DB transactions?Commit local intent + outbox/idempotency, then perform external action with retry/reconciliation; avoid long cross-network transaction.Local PostgreSQL transaction cannot atomically commit arbitrary broker/payment API.“Call API inside BEGIN so it rolls back.”What if API succeeds but response is lost?150,153
SQ017When choose Serializable instead of explicit locks?Cross-row/predicate invariants where SSI can detect dangerous dependency patterns and retry is acceptable; locks may be simpler for small known resource sets.Both are tools; choose based on invariant/contention.“Serializable always replaces locking.”What is write skew?66 — Serializable
SQ018How do you implement transaction retries safely?Retry whole transaction on classified 40001/40P01 with bounded backoff/jitter; keep external effects idempotent/outbox; cap attempts and surface failure.Only retriable errors should loop.“Retry every SQL error forever.”Why not retry just COMMIT?66,154
SQ019How do you diagnose deadlocks?Capture deadlock logs/lock graph, identify resources/order, trace transaction code, impose consistent lock ordering/shorter scope/indexes; keep retries as safety.Repeated deadlocks indicate design issue.“Increase deadlock_timeout until they disappear.”How can FK scans contribute?65,109
SQ020How do long transactions harm the system?Hold locks/snapshots/xmin horizons, delay vacuum, increase bloat, block DDL, complicate standby conflicts and consume pooled connections.Transaction duration is operational state.“Only long-running UPDATEs matter.”What about idle in transaction?110 — Long Transactions
SQ021Autovacuum falls behind on 1B-row table. What do you change?Remove horizon blockers, inspect change/dead rate/vacuum duration, lower per-table scale factors/thresholds, adequate workers/cost/I/O, index/HOT/fillfactor, partition if lifecycle justifies.Tune from absolute changes and capacity.“Disable autovacuum and run nightly VACUUM FULL.”How monitor progress?76,114 — Autovacuum
SQ022How do you tell bloat from simply large live data?Compare live/dead stats, relation/page utilization and growth/workload history; use page/extension estimates carefully; relate to query I/O before rewrite.File size alone is not bloat.“Large table means bloated.”REINDEX vs VACUUM FULL?78 — Bloat
SQ023When would you use VACUUM FULL?Exceptional need to physically compact/return space when exclusive rewrite downtime and disk requirements are acceptable.It is disruptive and not preventive maintenance.“After every large DELETE.”Online alternatives?75,78
SQ024Why can adding indexes worsen update-heavy tables?More index entries/WAL/cache/storage/vacuum work; indexed-column updates can prevent HOT; contention/build costs.Read gains have write-system cost.“Writes update heap only.”How measure HOT ratio?57,77
SQ025How do you tune fillfactor?For hot update workloads, lower table fillfactor to reserve page room, compare HOT/update/bloat/read-density trade-off under representative load.It is workload-specific, not global.“Set every table to 70.”What about B-tree fillfactor?77 — HOT Updates
SQ026How do you investigate WAL explosion?Identify write/backfill/index/checkpoint/FPI activity, slots/archive failures, table/index churn; inspect pg_stat_wal/WAL EXPLAIN and deployment timeline.WAL volume follows physical changes and retention.“Delete pg_wal files.”How can checkpoint frequency matter?82,113,159
SQ027Inactive slot is filling disk. What do you do?Identify consumer/required recovery position, add headroom/repair consumer; if retired or resync accepted, drop slot via SQL; never delete WAL files manually.Slot retention is a consumer contract.“Remove old files from pg_wal.”How cap retained WAL?137 — Replication Slots
SQ028How do you define backup strategy?Start with failure model/RPO/RTO; combine physical base + WAL/PITR and logical backups as useful, independent storage/encryption/retention, automated monitoring and restore drills.Backup choice follows recovery objective.“Nightly pg_dump is enough for every system.”How verify backup?85–87 — Backup/PITR
SQ029How do you test disaster recovery?Restore to isolated environment, time every step, verify server/config/extensions/roles/schema/data/constraints/app smoke, PITR target if applicable, document gaps.A successful command is not a recovered service.“Check backup file exists.”How often drill?86 — DR
SQ030Primary fails: what must HA system do beyond promotion?Detect failure, select/promote safe standby, fence old primary, route connections, reset/retry clients, validate lag/RPO, rejoin/rebuild old node.HA is system orchestration, not one SQL command.“Run pg_ctl promote and done.”What is split brain?90 — HA
SQ031How do you choose synchronous replication?From acknowledged-data-loss tolerance vs write latency/availability; select sync standby/quorum/ack stage and failure policy; load-test cross-zone latency.Sync durability has service dependency cost.“Always synchronous in production.”What if no sync standby reachable?88,90
SQ032How do you route read replicas safely?Classify endpoints by staleness/read-your-write needs; monitor replay lag; use primary/sticky/LSN wait for consistency-sensitive reads; fail closed/open per requirement.Replica reads are a consistency decision.“All SELECTs go to replicas.”Checkout confirmation example?143,163
SQ033When would you use logical replication for upgrade?Run new major in parallel, replicate selected tables, validate/catch up, coordinate schema/sequences/cutover; useful for low write downtime.It trades simple binary upgrade for dual-system complexity.“Logical replication copies every DB object automatically.”What needs manual handling?89,169
SQ034How do you migrate a 500M-row table safely?Expand schema, compatible code, concurrent indexes, bounded resumable backfill, NOT VALID/validate constraints, switch traffic, contract later; monitor locks/WAL/lag/SLO.Migration is multi-deploy workflow.“One ALTER + UPDATE transaction.”How set lock timeout?126–128
SQ035Why can transactional DDL still cause outage?DDL may need strong locks or rewrites; rollback safety does not prevent blocked traffic, WAL spike, long transaction or replica lag.Atomicity and availability are different.“If it rolls back, it is zero downtime.”How rehearse lock behavior?125 — Migrations
SQ036How do you add NOT NULL online?Backfill nulls, add CHECK(col IS NOT NULL) NOT VALID, validate, then SET NOT NULL after PG-version-specific rehearsal; separate lock/scan phases.Avoid one large blocking scan/change.“SET NOT NULL is always metadata-only.”Why validate check first?126 — Zero-Downtime Migrations
SQ037How do you add a unique constraint online?Resolve duplicates; create unique index concurrently; attach it as constraint when shape/support permits; monitor invalid index state.Expensive build can happen with reduced write blocking.“ALTER TABLE ADD UNIQUE on huge table during peak.”What if concurrent build fails?127 — Concurrent Index
SQ038Why is dual-write migration risky?Two write paths can diverge on partial failure/retries/order, creating two sources of truth.Prefer one authoritative transactional path or explicit reconciliation.“Writing both columns guarantees compatibility.”How validate parity?126 — Zero-Downtime Migrations
SQ039How do you design multi-tenant shared-schema keys?Tenant ID in tenant-owned PK/unique/FK/index paths; composite FK prevents cross-tenant relation; RLS defense; runtime role non-bypass.Isolation must exist in relationships, not only filters.“Globally unique UUID means tenant_id need not be enforced.”Per-tenant slug uniqueness?49, Project 6
SQ040How do you test RLS?Positive/negative CRUD for multiple tenants, joins/functions/views/background jobs, missing context, owner/bypass roles, pooled reuse, migrations.Security tests should prove denial paths.“One SELECT test is enough.”What does FORCE RLS change?96 — RLS
SQ041Shared schema vs schema-per-tenant vs DB-per-tenant?Shared is operationally efficient but row isolation critical; schema adds object separation/migration/catalog cost; DB adds stronger operational boundary but fleet cost/cross-tenant complexity.Choose by compliance, tenant scale/size, restore/customization/noisy-neighbor needs.“DB-per-tenant is always most secure and therefore best.”Hybrid isolation tier?49 — Multi-Tenant Design
SQ042How do you design per-tenant restore?If shared schema, logical extraction/PITR-to-scratch plus tenant copy is needed; schema/DB-per-tenant can simplify granularity; maintain FK/sequence/audit consistency.Restore granularity is an architecture driver.“PITR can restore one tenant directly in place.”What data dependencies complicate it?49,86
SQ043When should JSONB become relational columns?When keys become stable, required, joined, common filters/sorts, constraints/FKs, independently updated, or planner statistics matter.Hybrid schema preserves flexibility without sacrificing invariants.“Keep everything JSON for schema agility.”How migrate hot JSON key online?16,126
SQ044How do you design soft delete?Define lifecycle/legal need, deleted_at, active partial uniqueness/indexes, FK semantics, default query scope, archival/purge and restoration rules.Soft delete affects every query/invariant.“Add deleted_at and filter sometimes.”When hard delete required?147 — Soft Delete
SQ045How do you design audit logging?Define actor/action/time/before-after/reason/correlation/retention/access; append-only privilege model; same-transaction DB audit when needed; external immutable storage for stronger evidence.Audit is security/data-governance design.“Turn on log_statement=all forever.”Trigger vs application audit?146 — Auditing
SQ046How do you protect sensitive query logs?Prefer fingerprints/durations, redact/suppress bind values, restrict log access/retention, classify PII and rotate storage.Logs become secondary data stores.“Logs are internal, so privacy does not apply.”What should traces record?133,134
SQ047What is a good timeout strategy?Layer request deadline, pool queue timeout, statement timeout, smaller lock timeout, idle transaction timeout; vary by workload and cancel server work.Timeouts bound resource occupancy and failure propagation.“One global 30s timeout.”Migration timeout policy?135 — Timeouts
SQ048What is load shedding for PostgreSQL-backed APIs?Bound pools/queues, reject/degrade excess work before saturating DB, prioritize critical workload, cache/read-only fallback where valid.Controlled queueing beats connection storm.“Let every request open a connection.”What metric triggers shedding?136 — Resource Limits
SQ049How do you separate OLTP and analytics?Keep operational queries bounded; use replicas/materialized/report tables or separate analytics system when heavy scans contend with OLTP; define freshness/ETL.Resource isolation and workload shapes differ.“Partitioning alone isolates CPU/I/O.”When use materialized view?40,192
SQ050When partition a table?When pruning/lifecycle/maintenance/attach-detach/local indexes materially help very large data with suitable key; not merely because row count is high.Operational benefits often matter as much as speed.“Partition at 10M rows automatically.”How choose granularity?115 — Partitioning
SQ051What makes too many partitions harmful?Planning/catalog memory/time, many indexes/files, vacuum/DDL/monitoring complexity, cross-partition operations.Partition count itself is a cost.“More partitions means less work always.”Alternative for time data?115 — Partitioning
SQ052When shard PostgreSQL?Only after local/vertical/query/index/cache/replica/partition options are insufficient and explicit write scale, residency, isolation or latency requirements justify distributed complexity.Sharding changes transactions/joins/uniqueness/failover.“Shard early to future-proof.”How choose shard key?116 — Sharding
SQ053What makes a good shard key?High-cardinality stable routing key aligned with transaction/query locality and balanced distribution, with a rebalancing/global-ID strategy.Poor keys create hot shards/cross-shard work.“Primary key UUID automatically.”Tenant ID pros/cons?116 — Sharding
SQ054How do you handle global uniqueness across shards?Central authority/ID scheme, directory service, scoped uniqueness, or distributed coordination depending requirement; avoid pretending local UNIQUE is global.Uniqueness boundary follows storage/coordination boundary.“Create same unique index on each shard.”Email uniqueness example?116 — Sharding
SQ055When use FDW vs ETL?FDW for live federated access with acceptable network/transaction semantics; ETL/materialization for repeated large analytics, isolation, resilience, predictable performance.Remote query is distributed and latency-sensitive.“FDW makes remote data local.”How inspect pushdown?117 — FDWs
SQ056How would you performance-test PostgreSQL?Production-like data distribution/size, mixed workload/concurrency, p50/p95/p99, throughput, pool waits, CPU/I/O/temp/WAL/locks, plan capture; compare before/after.Single-query microbenchmarks miss system effects.“Run EXPLAIN once on staging.”What does pgbench offer?131,132
SQ057Why can average latency hide incidents?Tail percentiles reveal queueing/lock/spill/outlier behavior experienced by users; averages can remain low while p99 explodes.SLOs are distribution-sensitive.“Average is enough if sample is large.”How correlate p99 to DB?133 — Observability
SQ058How do you use pg_stat_statements responsibly?Enable with understood overhead/config, rank total/mean/calls/I/O/WAL, correlate queryid to app/traces, preserve history externally, account resets.It aggregates fingerprints, not full causal context.“The slowest mean query is always top priority.”What gets normalized?105 — pg_stat_statements
SQ059What is a query fingerprint?Normalized representation/queryid grouping structurally equivalent statements independent of literal values.Lets workload stats aggregate repeated query shapes.“Hash of returned rows.”Parameter skew limitation?105 — pg_stat_statements
SQ060What is observability vs monitoring?Monitoring tracks known signals/alerts; observability combines metrics/logs/traces/query state so unfamiliar failures can be investigated.Database incidents need correlation across layers.“They are exact synonyms.”Which DB signals link to traces?133 — Observability
SQ061How do you respond to disk almost full?Identify growth source (relations, WAL/slots, temp, logs/archive), stop unsafe growth/add capacity via supported operations, preserve recovery, then fix root cause.Deleting data-directory files can corrupt DB.“Delete old pg_wal files.”What if slot is cause?138,159
SQ062How do you respond to XID age alert?Find blockers/old transactions, let/tune anti-wraparound vacuum, ensure I/O/space, monitor age decreasing; prioritize correctness.Anti-wraparound work is mandatory.“Cancel vacuum to restore latency.”What is freezing?172 — XIDs
SQ063How do you respond to replica lag?Identify send/write/flush/replay stage, primary WAL rate, network, standby I/O/CPU, long queries/conflicts; route reads/failover decisions according to lag budget.“Restart replica” is not diagnosis.“Lag is only network.”What if replay lag only?88,159
SQ064How do you investigate archive failures?pg_stat_archiver/logs/object storage/credentials/commands; verify continuity and backlog, repair and confirm new segments archive before restoring RPO claims.Last successful backup does not prove WAL continuity.“Backup job green means PITR green.”How test archive restore?87,159
SQ065What is capacity planning for PostgreSQL?Forecast heap/index/WAL/backup/temp growth, peak QPS/TPS/concurrency, CPU/memory/I/O, restore time, migration headroom and expansion lead time.Capacity is multi-dimensional and includes transient operations.“Alert at 80% disk.”How model index-build space?162 — Capacity Planning
SQ066How do you scale reads?Optimize query shape/indexes first, cache/precompute if appropriate, vertically scale, add replicas with staleness policy, then broader architecture as justified.Replicas replicate inefficient workload too.“Add replicas first.”When cache beats replica?163 — Scaling Reads
SQ067How do you scale writes?Reduce write amplification, batch/COPY, resolve hot contention, efficient schema/indexes/WAL/storage, vertical scale; partition/shard only for explicit limits.Write bottleneck type determines solution.“Read replicas scale writes.”What is a hot counter solution?164 — Scaling Writes
SQ068COPY vs multi-row INSERT?COPY uses bulk protocol/path with lower per-statement overhead; multi-row INSERT still useful for moderate batches and RETURNING/upsert semantics.Constraints/indexes/WAL still apply.“COPY bypasses constraints and WAL automatically.”\copy vs COPY?165,166
SQ069Why use staging tables for imports?Separate ingestion/parsing from validation/deduplication/typed merge; support retry and controlled target transactions.Bulk source quality should not directly mutate core tables.“Load CSV straight into production target always.”Temp vs unlogged vs logged staging?165 — Bulk Import
SQ070How do you design a DB-backed job queue?Ready index, short claim transaction with SKIP LOCKED, status/lease/attempts/run_at, idempotent worker effects, retry/dead-letter, cleanup/vacuum monitoring.DB lock is for claiming, not holding during job execution.“Keep FOR UPDATE transaction open until job finishes.”How recover crashed worker?145, Project 8
SQ071When should you use a broker instead of PostgreSQL queue?When fan-out, stream retention/replay, protocol routing, extreme throughput, independent service decoupling or broker-native delivery semantics dominate.Tool choice follows requirements.“PostgreSQL can never be a queue.”What DB queue advantage?145 — Queue Pattern
SQ072How do you model temporal history?Separate valid time/system time/current state; use immutable versions/events/ranges and exclusion where no-overlap; preserve audit provenance.Overwriting current row loses historical truth.“updated_at is complete history.”Bitemporal example?148 — Temporal Modelling
SQ073Event sourcing vs relational current state?Event sourcing makes append-only domain events source of truth and projections derived; useful when history/replay is core, but adds ordering/version/rebuild complexity.Do not adopt solely for scale fashion.“Event sourcing is just an audit table.”When ordinary audit is enough?149 — Event Sourcing
SQ074How would you use pgvector in a relational app?Store vector alongside typed tenant/document/permission metadata; filter authorization/metadata, choose exact/ANN index by recall/latency, benchmark extension version/workload.Vector search does not replace relational security/model.“Put all metadata in embedding payload.”What is RAG provenance?185,186
SQ075What is extension governance?Approved extensions/versions, trust/native code review, managed-provider availability, schema/privileges, backup/restore, upgrade compatibility and ownership.Extensions become platform dependencies.“CREATE EXTENSION is just installing a library.”PostGIS/pgvector upgrade concern?104,183
SQ076How do you plan a major PostgreSQL upgrade?Review release notes/extensions/drivers, rehearse prod-sized clone, choose pg_upgrade/dump/logical path, backup/rollback, compare tests/plans/perf/HA, cut over and monitor.Major upgrade is system change.“Minor-like package update.”PG18 pg_upgrade statistics improvement?169 — Versioning/Upgrades
SQ077Why keep minor releases current?Supported minor releases are cumulative bug/security fixes for the major; postponing leaves known fixes unapplied.PostgreSQL version policy expects minor maintenance.“Minor releases add breaking features, so avoid them.”What’s current PG18 minor?Version Baseline
SQ078What is your production PostgreSQL readiness checklist?Recovery proof, HA/RPO/RTO, pools/timeouts, workload plans/stats, vacuum/XID, WAL/slots/disk, least privilege/TLS/RLS, migrations, monitoring/runbooks/version policy.Readiness spans correctness and operations.“Backups + monitoring = ready.”Which item would block launch?161 — Production Readiness
SQ079What makes a database incident postmortem useful?Timeline, impact, detection, contributing/root causes, response/recovery, why controls failed, concrete owners/actions/tests/runbook/monitoring improvements; blameless but specific.Prevent recurrence via system changes.“Name who ran the bad query.”How validate action items?159,160
SQ080What differentiates senior PostgreSQL engineering?Mechanism/trade-off reasoning across schema, SQL, concurrency, planner, maintenance, recovery/security/ops, plus reusable team guardrails and mentoring.Seniority is not memorizing more syntax.“Knowing every GUC by heart.”Give an example organizational guardrail.190 — Senior PostgreSQL Engineering