Skip to main content

Advanced — AQ001–AQ080

IDQuestionExpected answerReasoningCommon wrong answerFollow-upRelated chapter
AQ001How would you solve top-N-per-group?Use row_number/rank over partition or LATERAL top-N lookup; choose based on tie semantics, indexes, group count, and plan.Different formulations can produce very different work.“GROUP BY with LIMIT N.” LIMIT is global.Which index favors LATERAL?32, 37 — Lateral/Windows
AQ002How do you solve gaps and islands?Detect gaps with LAG, create a start flag, cumulative-sum into island IDs; for consecutive dates a normalized row-number key can work.The problem is grouping contiguous ordered values.“GROUP BY date.”How handle overlapping intervals?37 — Window Functions
AQ003How do you sessionize events?Partition by user, order events, compare LAG timestamp to inactivity threshold, flag new sessions, cumulative-sum flags.Session boundaries depend on temporal gaps and deterministic ordering.“GROUP BY user and day.”What if equal timestamps?37 — Window Functions
AQ004How do you compute cohort retention?Assign each user a cohort period, derive distinct activity periods, join activity >= cohort, aggregate retained users against cohort size.Denominator is the original cohort, not active users that month.“Monthly active users divided by total users.”How handle late events?192 — System Design
AQ005How do you model a funnel in SQL?Find ordered first occurrences or sequence states per user/session; require each later step after previous step; aggregate conversion.Existence alone does not prove order.“Count each event type globally.”What about repeated funnel attempts?37 — Windows
AQ006How do you find median in PostgreSQL?Ordered-set aggregate such as percentile_cont(0.5) WITHIN GROUP (ORDER BY x) or percentile_disc for observed value.Median is not ordinary AVG.“AVG is the median.”cont vs disc?28 — Aggregates
AQ007Why can DISTINCT ON be useful?PostgreSQL extension selecting first row per distinct prefix under explicit ORDER BY; concise latest-per-group.It is efficient/readable when ordering/index match.“Standard SQL feature.”Portable alternative?38 — Advanced Querying
AQ008When would you prefer LATERAL over a window for top-N?When parent set is limited and an index can cheaply fetch N children per parent; window may scan/sort the whole child set.Parameterized lookup can reduce global work.“LATERAL is always faster.”When window wins?32 — Lateral Queries
AQ009Why is RANGE different from ROWS?ROWS counts physical ordered rows; RANGE uses ordering value/peer semantics and can include multiple tied rows or value-based ranges.Frame choice changes results with ties.“They are aliases.”What is GROUPS?37 — Window Functions
AQ010What is relational division?Querying entities related to all members of a required set, often via double NOT EXISTS or count comparison.It expresses universal quantification.“A numeric division operator.”Give customer-bought-all-products query idea.31 — Subqueries
AQ011Why can a correlated subquery be fast?Planner may decorrelate it or execute selective indexed parameterized lookups; syntax alone does not determine physical repetition.Plans, not folklore, determine cost.“Correlated subqueries always cause N+1.”How prove?31,70 — Subqueries/EXPLAIN
AQ012What is query decorrelation?Transforming correlated subquery logic into joins/semi-joins/aggregates or other set-based plan structures.Optimizer preserves semantics while changing evaluation shape.“Removing all subqueries manually.”When might correlation remain?31 — Subqueries
AQ013What does CTE MATERIALIZED trade off?Forces one materialized evaluation/reuse but blocks predicate pushdown/join reordering across boundary.Useful only when saved recomputation outweighs lost optimization/storage.“MATERIALIZED is a performance hint that always helps.”When use NOT MATERIALIZED?34 — CTEs
AQ014What are data-modifying CTE risks?Multiple modifying substatements share statement snapshot/semantics that can be non-obvious; execution ordering should not be assumed beyond documented dependencies/RETURNING.Complex write CTEs can hide interactions.“They execute textually top to bottom.”Safer alternative?34 — CTEs
AQ015How do you prevent recursive CTE cycles?Track visited IDs/path or use SQL SEARCH/CYCLE support; stop recursion on revisits.Graphs may contain cycles even if intended as trees.“UNION ALL eventually stops automatically.”UNION vs UNION ALL effect?35 — Recursive CTEs
AQ016Why use range exclusion for bookings?It atomically enforces non-overlap under concurrent inserts using equality/overlap operators and GiST support.Check-then-insert has a race window.“SELECT overlap first is enough.”What about cancelled bookings?17,42 — Ranges/Constraints
AQ017How would you index JSONB?Choose GIN operator class for supported containment/path workload, or expression B-tree indexes for stable hot fields; measure update/index size cost.One broad GIN is not universally optimal.“Always add GIN(attributes).”jsonb_ops vs jsonb_path_ops?16,53 — JSONB/GIN
AQ018Why can updating one JSONB field be expensive?Row version contains a new JSONB value; TOAST/compression/decomposition and GIN/expression index maintenance may touch substantial data.JSON documents are not independently stored fields by default.“PostgreSQL changes bytes in place.”When normalize the field?16,80 — JSONB/TOAST
AQ019What does BRIN summarize?Values over ranges of heap blocks using operator-class summaries such as min/max.It skips block ranges that cannot match rather than locating exact rows.“One index entry per row.”Why does correlation matter?56 — BRIN
AQ020What is GiST conceptually?Extensible generalized search tree framework whose operator class defines search/penalty/split semantics.It supports ranges, geometric/spatial, exclusion and extensions.“A built-in geospatial-only index.”GiST vs GIN?54 — GiST
AQ021What is SP-GiST conceptually?Space-partitioned generalized index framework suited to recursively partitionable search spaces depending on operator class.Different data structures can exploit tries/quad-style partitions.“A smaller GiST.”Give a use-case class.55 — SP-GiST
AQ022Why does multicolumn B-tree order matter?Leading equalities/ranges, requested ordering, skip-scan possibilities, and workload reuse determine accessible key ranges/order.Index is lexicographically structured.“Put highest cardinality first always.”PG18 skip scan impact?51 — B-Tree
AQ023What is B-tree skip scan?Planner can use repeated searches over missing earlier key values in suitable multicolumn indexes, expanded/improved in PG18.It broadens index usefulness but does not erase order design.“It skips heap pages like BRIN.”When still create another index?51 — B-Tree
AQ024How do collation and operator class affect indexes?They define comparison/operator semantics the index supports; query operator/collation must be compatible.Index usefulness is semantic, not just column presence.“Any text predicate uses any text index.”LIKE prefix indexing issue?57 — Advanced Indexes
AQ025Why might lower(email) not use an index on email?The predicate applies a function whose result is not ordinary raw-column ordering; use matching expression index or different semantics.Sargability/operator matching matters.“Planner is broken.”Create index?57 — Advanced Indexes
AQ026What is selectivity?Estimated fraction of rows satisfying a predicate.It strongly affects whether index or sequential access is cheaper.“Number of distinct columns.”How does MCV data help?69,73 — Planner/Stats
AQ027What is cardinality estimation?Planner estimation of row counts at base filters and intermediate plan nodes.Join/order/aggregate cost compounds on these estimates.“Exact count from table before planning.”Why can 100× error matter?69 — Query Planner
AQ028What is physical correlation statistic?Relationship between column order and heap physical order used in cost estimation for index access.High correlation makes range index scans more sequential/cheaper.“Correlation between two business columns.”Extended stats cover what instead?73 — Query Statistics
AQ029Why can extended statistics improve a plan?They model cross-column dependencies/MCVs/distinctness when independent selectivity multiplication is wrong.Better row estimates lead to better paths/join order.“They force a specific index.”When ANALYZE after CREATE STATISTICS?73 — Query Statistics
AQ030What is a generic prepared plan?A plan reused without tailoring to each parameter value when PostgreSQL estimates reuse is worthwhile.Can be bad under parameter skew.“Prepared statements always have one fixed plan immediately.”Custom plan?120 — Prepared Statements
AQ031How do you diagnose parameter-sensitive plans?Compare representative hot/cold bind values, generic/custom behavior, statistics, actual rows/buffers and workload frequency.One parameter distribution can justify different scans.“Disable prepared statements globally.”What if one tenant owns 50% of rows?120 — Prepared Statements
AQ032Why is work_mem × max_connections not a memory formula?Work memory is per sort/hash-like operation and can multiply per query/parallel worker; not every connection uses it simultaneously.Aggregate memory depends on plans and concurrency.“That product is exact PostgreSQL RAM use.”How would you size/test?112 — Memory Config
AQ033What happens when a sort exceeds work_mem?It can spill to temporary files using external sort methods, increasing I/O/latency.EXPLAIN reports sort method/temp activity.“PostgreSQL kills the query.”How detect workload spills?70,112 — EXPLAIN/Memory
AQ034What happens when a hash join/aggregate exceeds memory?It can batch/spill partitions to disk depending on plan/node and memory rules.Batches and temp I/O expose pressure.“Hash table always stays fully in RAM.”Is raising work_mem always safe?72,112 — Join/Memory
AQ035Why can a Nested Loop explode?Underestimated outer rows cause an inner operation to execute far more times than planned.loops reveals multiplication.“Nested Loop is always bad.”Fix root estimate or access path?72 — Join Algorithms
AQ036What is Memoize?Plan node caching results of parameterized subplan lookups for repeated parameter values.Can reduce repeated inner work in nested-loop-like plans.“Materializes entire table.”When would hit rate be low?71 — Plan Nodes
AQ037Why can EXPLAIN ANALYZE timing mislead?It is one execution affected by cache, instrumentation, load, parameters and may execute DML; workload frequency matters.Use representative repeated measurements and system metrics.“One fast run proves optimization.”Why use BUFFERS?70,74 — EXPLAIN/Performance
AQ038How do you distinguish lock wait from slow execution?Inspect pg_stat_activity wait events/blockers; a waiting query may have a fine plan but be blocked.Performance includes queuing/locks.“Add an index first.”Root blocker query?109 — Lock Monitoring
AQ039What is an advisory lock?Application-defined integer-key lock, session or transaction scoped, not tied automatically to a row.Useful for coarse coordination when key semantics are designed carefully.“Database understands which table row it protects.”Row lock alternative?64 — Locking
AQ040Row lock modes: why more than FOR UPDATE?FOR NO KEY UPDATE, FOR SHARE, and FOR KEY SHARE allow different compatible/conflicting access, supporting FK/key semantics with less blocking.Use weakest correct mode.“All row locks are exclusive.”Which mode does ordinary UPDATE take?64 — Locking
AQ041What is write skew?Two transactions read a shared predicate/invariant, update different rows, and both commit producing invalid combined state under snapshot isolation.Row write conflicts may not occur because rows differ.“Same as dirty read.”How does Serializable help?63,66 — Isolation/Serializable
AQ042How does SSI differ from locking every predicate?PostgreSQL tracks serialization dependencies/predicate conflict information on MVCC snapshots and aborts dangerous cycles instead of serializing all reads with blocking locks.Provides serializable outcome with optimistic conflict detection.“Serializable means table locks.”What error must app retry?66 — Serializable
AQ043Why deterministic lock ordering reduces deadlocks?Transactions acquire shared resource sets in same order, preventing cycles where each holds a resource the other wants earlier.Waits may remain, but cyclic waits shrink.“It removes all contention.”Transfer example?65 — Deadlocks
AQ044Why not hold a DB transaction during HTTP call?Locks/snapshots/connections stay open across unpredictable latency/failure, increasing contention and vacuum impact.Commit local intent then coordinate external effects idempotently/outbox.“It guarantees distributed atomicity.”What pattern replaces it?153 — Transaction Boundaries
AQ045What is idempotency at the DB boundary?A unique operation key stored with the business effect so retries map to one logical result.Handles ambiguous client/network retries.“Ignore any repeated payload.”Why hash request body?151 — Idempotency
AQ046What is the outbox pattern?Store business change and publish-intent row in one DB transaction; async publisher delivers with retry; consumers handle duplicates.Avoids impossible atomic commit across DB + broker without distributed transaction.“Publish to broker then insert DB row.”Why can duplicates still occur?150 — Outbox Pattern
AQ047Why are outbox consumers idempotent?Publisher may deliver then lose acknowledgement and retry; at-least-once delivery creates duplicates.Exactly-once effect needs application/domain dedupe.“Primary key on outbox guarantees broker once.”Where store consumer dedupe?150,151 — Outbox/Idempotency
AQ048How does RLS interact with pooling?Session state can leak across reused connections; set tenant context transaction-locally and reset/bound it, use non-bypass runtime role.Pooling changes session continuity assumptions.“RLS is automatic after authentication.”Session vs transaction pooling?96,91 — RLS/Connections
AQ049USING vs WITH CHECK in RLS?USING controls which existing rows are visible/targetable; WITH CHECK controls rows permitted after INSERT/UPDATE.Read and write policy questions differ.“USING alone validates inserts.”FORCE ROW LEVEL SECURITY?96 — RLS
AQ050Why are SECURITY DEFINER functions risky?They run with owner privileges; unsafe search path, dynamic SQL or broad execute grants can escalate access.Elevated execution is a privilege boundary.“Stored procedures are inherently safe.”How harden search_path?98 — Functions
AQ051What does function volatility tell PostgreSQL?IMMUTABLE/STABLE/VOLATILE describe whether results can change and side effects/statement stability, affecting planning/execution assumptions.Mislabeling can make results incorrect.“A performance optimization flag only.”Why is now() STABLE-like?98 — Functions
AQ052Functions vs procedures in PostgreSQL?Functions return values and participate in expressions; procedures are invoked with CALL and can perform transaction control in permitted contexts.They serve different SQL/programming roles.“Procedure is just a void function.”When use SQL function?98,99 — Functions/Procedures
AQ053Why are triggers risky despite usefulness?Hidden writes, recursion/order interactions, bulk overhead and debugging/migration surprises.Prefer declarative constraints/generated expressions when possible.“Triggers guarantee cleaner architecture.”Good trigger use-case?101 — Triggers
AQ054Full-text search vs ILIKE '%term%'?FTS tokenizes/normalizes linguistic lexemes and supports ranking; substring LIKE is literal pattern matching and needs different indexing.They answer different search semantics.“GIN makes LIKE and FTS equivalent.”Where pg_trgm fits?103 — Full-Text Search
AQ055tsvector vs tsquery?tsvector is normalized searchable document lexemes; tsquery is normalized search expression matched with @@.Search configuration/dictionaries affect both.“Both store original text.”Why generated search vector?103 — FTS
AQ056What does VACUUM’s visibility map interaction enable?Marks pages all-visible/all-frozen when proven, enabling vacuum skipping and index-only scan visibility shortcuts.VM connects maintenance to query performance.“VACUUM rebuilds indexes.”What clears all-visible?75,175 — Vacuum/VM
AQ057What is XID wraparound risk?Finite transaction IDs use relative age; very old tuple XIDs must be frozen before numeric wrap could make visibility comparisons unsafe.Anti-wraparound vacuum protects correctness.“Sequence IDs wrap.”What metric monitor?172 — XIDs
AQ058What is MultiXact?Representation of multiple transactions sharing row-lock membership; has its own finite IDs/member storage and vacuum age concerns.Common with shared/key locks and FK-related activity.“Multiple transactions committed as one.”How monitor age?173 — MultiXacts
AQ059What is TOAST?PostgreSQL mechanism compressing and/or storing large variable-width attributes out-of-line in chunks.Keeps heap tuples/pages manageable.“A cache for JSON.”Why can large JSON updates still cost?80 — TOAST
AQ060What is the free space map?Reconstructible per-relation metadata summarizing page free space to guide tuple placement.Avoids scanning pages to find room.“The same as visibility map.”What does VM track?174 — FSM
AQ061What are dirty buffers?Shared buffers modified in memory whose corresponding data pages have not yet been written to durable storage.WAL ordering permits delayed page writes.“Uncommitted rows only.”Who writes dirty pages?81 — Buffer Management
AQ062Why must WAL be written before data page?Crash recovery needs redo information durable before a possibly partial/new data-page state reaches disk.Core write-ahead invariant protects consistency.“Because WAL is the backup.”What is full-page image?82,178 — WAL
AQ063What is a full-page image in WAL?First change after checkpoint can log whole page image so crash recovery can repair torn-page risk.Explains some checkpoint-related WAL volume.“Every WAL record contains whole row/table.”How can wal_compression affect it?178 — WAL Internals
AQ064Why can frequent checkpoints increase WAL?More pages incur first-change full-page images after each checkpoint and write bursts may increase.Checkpoint frequency has WAL/I/O trade-offs.“Checkpoints delete WAL, so more is always better.”Which settings influence frequency?83 — Checkpoints
AQ065What is crash recovery?On unclean start PostgreSQL replays WAL from recovery/checkpoint state to reconstruct consistent pages/transactions.Committed WAL can restore pages not flushed at commit.“Restore latest backup on every crash.”What about unlogged tables?84 — Crash Recovery
AQ066Why is replica not backup?Logical mistakes/drop/corruption can replicate; replica optimizes availability/read scale, while backups provide independent historical recovery.Different failure models.“Any second copy is a backup.”What protects accidental DELETE?189 — Reliability Architecture
AQ067What is a replication slot?Keeps WAL/logical decoding state needed by a consumer from being removed too early.Consumer reliability trades against retained disk.“A reserved standby connection.”Failure mode if consumer stops?137 — Replication Slots
AQ068Physical vs logical replication?Physical streams WAL/page-level cluster changes to compatible standby; logical publishes row-level changes for selected tables via publications/subscriptions.Granularity/use cases/schema semantics differ.“Logical is just slower physical.”Upgrade use-case?88,89 — Replication
AQ069What is replica identity?Key/row identity logical replication uses to identify rows for UPDATE/DELETE; PK normally ideal, FULL logs old row when needed.Logical changes need target-row identification.“Replication slot name.”Cost of REPLICA IDENTITY FULL?89 — Logical Replication
AQ070What is synchronous replication trade-off?Waiting for standby acknowledgement reduces acknowledged data-loss window but increases commit latency and dependency on standby/network.RPO, latency and availability are coupled.“Synchronous guarantees no failover complexity.”Quorum sync?90 — HA
AQ071What is split brain?More than one node accepts incompatible writes as primary/leader due to failed coordination/partition.Must prevent with promotion authority and fencing.“A lagging replica.”What is fencing?90 — HA
AQ072What is partition pruning?Planner/executor excludes partitions whose bounds cannot satisfy the query predicate.Main query-performance benefit of partitioning is skipping relations.“PostgreSQL scans every partition but indexes it.”Runtime pruning?115 — Partitioning
AQ073Why can partitioning hurt?Excess partitions increase planning/catalog/maintenance complexity; cross-partition queries still work; uniqueness/index constraints become harder.It is an operational/data-lifecycle tool, not automatic speed.“More partitions always means less data scanned.”When is BRIN simpler?115 — Partitioning
AQ074Why is partitioning not sharding?Partitioning divides one logical table within one PostgreSQL server; sharding distributes rows across servers and adds routing/distributed semantics.Physical failure/transaction boundaries differ.“Both mean horizontal split, therefore same.”What new sharding problems appear?116 — Sharding
AQ075What is FDW pushdown?Foreign data wrapper sends eligible filter/join/aggregate work to remote server instead of transferring all rows locally.Network and remote capabilities make plan placement important.“Foreign table always behaves exactly like local table.”How inspect remote SQL?117 — FDWs
AQ076Why can parallel query be slower?Worker startup/coordination/merge costs and resource contention can exceed benefit for small/latency-sensitive queries.Parallelism is costed, not free.“More workers always reduce latency.”Gather vs Gather Merge?118 — Parallel Query
AQ077When can JIT hurt?Compilation startup cost can exceed saved CPU on short OLTP queries.JIT benefits CPU-heavy long execution when amortized.“JIT makes all SQL compiled and faster.”How inspect JIT timing?119 — JIT
AQ078What makes CREATE INDEX CONCURRENTLY special?Builds index while allowing normal writes through multiple phases; cannot run in regular transaction block and failure can leave invalid index.Production migration code must inspect/retry state.“It is identical but faster.”Why can long transactions delay it?127 — CREATE INDEX CONCURRENTLY
AQ079Why is expand/contract safer than direct rename/drop?Old/new app versions can coexist while schema expands, data backfills, traffic switches, then obsolete structure contracts later.Rolling deploy compatibility prevents outage.“Transactional DDL makes rename zero-risk.”Give NOT NULL sequence.126 — Zero-Downtime Migrations
AQ080How would you throttle a backfill?Small idempotent key-range batches committed independently; monitor API latency, locks, CPU/I/O, WAL, replica lag; pause/reduce rate when budgets exceed.Backfill is a production control loop, not one giant UPDATE.“Use the largest batch possible overnight.”How make it resumable?128 — Backfills