Skip to main content

Intermediate — IQ001–IQ080

IDQuestionExpected answerReasoningCommon wrong answerFollow-upRelated chapter
IQ001Why is SQL called declarative?You specify the desired result/state change while the optimizer chooses an execution strategy.Separates relational semantics from physical access path.“SQL executes clauses exactly top-to-bottom as written.”Logical vs physical order?03 — SQL Overview
IQ002What is logical SELECT processing order?Conceptually FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT/FETCH.Explains alias visibility and aggregate semantics without claiming physical order.“It is the exact executor plan.”Where can planner reorder work?24 — SELECT Fundamentals
IQ003Why is SELECT * risky in APIs?Transfers unnecessary data and couples consumers to schema changes; can prevent narrower/index-only access.Stable contracts should choose needed columns.“It is always slower in every query.”When is it fine?155 — SQL Style
IQ004Why should pagination ORDER BY be deterministic?Tied rows otherwise have no defined relative order, causing duplicates/misses between pages.Cursor/offset semantics need a total ordering.“The PK will be used automatically.”Add a compound cursor example.27 — Ordering and Pagination
IQ005Offset vs keyset pagination?OFFSET skips an increasing prefix; keyset resumes after the last ordered key and scales better for sequential navigation.Deep offset work and concurrent row shifts grow.“Keyset is always better; it supports arbitrary page numbers easily.”What must cursor encode?27 — Ordering and Pagination
IQ006Why use a compound keyset cursor?Non-unique primary sort values need a stable tie-breaker such as (created_at,id).Cursor must represent complete ordering state.“Timestamp alone is enough.”How handle nullable sort key?27 — Ordering and Pagination
IQ007What is a semi-join pattern in SQL?EXISTS or equivalent logic returning left rows when at least one match exists without multiplying output.It matches existence semantics.“INNER JOIN + DISTINCT is always identical and preferable.”What is an anti-join?31 — Subqueries
IQ008NOT EXISTS vs LEFT JOIN ... IS NULL?Both can express anti-join when written correctly; NOT EXISTS is often clearer and avoids accidental right-side column logic.Planner may transform both similarly.“LEFT JOIN is always faster.”Why avoid NOT IN with nullable source?26 — Filtering
IQ009What is join cardinality?The number/multiplicity of output row combinations implied by relationship/predicate.One-to-many and many-to-many relationships expand rows.“Number of columns in a join.”Why can aggregates double-count after joins?30 — Joins
IQ010How do you debug unexpected duplicate join rows?Establish intended output grain, inspect uniqueness/cardinality and predicates, count after each join; do not mask with DISTINCT.Duplicates usually reflect real multiplicity or missing conditions.“Add DISTINCT.”How model many-to-many?30 — Joins
IQ011What is a correlated subquery?A subquery referencing columns from an outer query row.It creates a parameterized semantic dependency, though planner may transform it.“It always executes once per row physically.”When use LATERAL instead?31 — Subqueries
IQ012What does LATERAL do?Lets a FROM item reference columns from preceding FROM items.Powerful for top-N per parent and set-returning functions.“It is just another LEFT JOIN keyword.”Give top-1-order example.32 — Lateral Queries
IQ013Window function vs GROUP BY aggregate?Window functions compute across related rows while preserving each input row; GROUP BY collapses to group grain.They solve different result shapes.“Window functions are just faster aggregates.”Can aggregate functions be used as windows?37 — Window Functions
IQ014ROW_NUMBER vs RANK vs DENSE_RANK?ROW_NUMBER uniquely sequences rows; RANK shares ties with gaps; DENSE_RANK shares ties without gaps.Choose according to tie semantics.“They differ only in performance.”Which solves third distinct salary?37 — Window Functions
IQ015What is a window frame?The subset of a window partition relative to the current row used by frame-sensitive functions/aggregates.ORDER BY alone does not fully define running/window semantics.“Same as PARTITION BY.”ROWS vs RANGE?37 — Window Functions
IQ016Why is LAST_VALUE often surprising?Default frame typically ends at current peer group/current row, so LAST_VALUE may not mean final partition value.Must define an appropriate frame for full-partition last value.“LAST_VALUE always returns partition’s last row.”Write the full frame.37 — Window Functions
IQ017What is a CTE?A named query subexpression introduced by WITH; can be recursive or data-modifying.Improves composition/readability and sometimes controls materialization.“A temporary table.”Are CTEs optimization fences?34 — CTEs
IQ018Are PostgreSQL CTEs always materialized?No; eligible non-recursive CTEs can be inlined. MATERIALIZED/NOT MATERIALIZED influence behavior.Modern PostgreSQL differs from old versions/tutorial folklore.“WITH always stores a temp result.”When force materialization?34 — CTEs
IQ019How does a recursive CTE work?Anchor rows seed a working set; recursive term repeatedly derives new rows until none remain, with UNION semantics controlling duplicates.It evaluates iterative recursion declaratively.“The recursive SELECT calls itself like a function.”How prevent cycles?35 — Recursive CTEs
IQ020UNION vs INTERSECT vs EXCEPT?Union combines sets, intersect keeps common rows, except keeps left rows absent from right; default forms dedupe.They are horizontal set operations over compatible columns.“They join tables by keys.”Why prefer UNION ALL sometimes?33 — Set Operations
IQ021What is IS DISTINCT FROM?Null-safe inequality treating NULL as a comparable state; inverse is IS NOT DISTINCT FROM.Avoids verbose null comparison logic.“Same as <>.”Use it in change detection.19 — NULL
IQ022Why can a CHECK allow NULL?A CHECK rejects FALSE, while UNKNOWN from a NULL-dependent expression is not FALSE.Pair with NOT NULL when absence is invalid.“CHECK(value > 0) implies NOT NULL.”Show correct positive required column.42 — Constraints
IQ023What is a domain type?A reusable PostgreSQL scalar type based on another type plus constraints/default semantics.Useful for stable repeated scalar meaning.“Same as a table lookup.”Domain vs enum?12 — Boolean, Enums, Domains
IQ024Enum vs lookup table?Enum fits small stable typed states; lookup table fits frequently evolving/configurable values with metadata/relationships.Migration/evolution requirements drive choice.“Enums are always faster, so always use them.”What are enum migration costs?12 — Boolean, Enums, Domains
IQ025text vs varchar(n) in PostgreSQL?text is appropriate for unconstrained strings; varchar(n) expresses a genuine maximum, not a performance optimization.PostgreSQL does not reward arbitrary length limits as many assume.“varchar is always faster/smaller.”When use char(n)?11 — Strings
IQ026numeric vs double precision?numeric is exact decimal/arbitrary precision; double is approximate floating point.Financial correctness often needs exact decimal semantics.“Double is fine for currency if rounded later.”What else must money model include?10 — Numeric Types
IQ027What does timestamptz store conceptually?An absolute instant normalized from input zone context and displayed in the session timezone; not the original named timezone.Prevents “timezone stored inside timestamp” misconception.“It stores timestamp plus timezone name.”When use timestamp without time zone?13 — Date and Time
IQ028Why can DST break naive scheduling?Local wall times can be ambiguous or nonexistent and offsets change by rule/date.Store instants plus zone/business intent when needed.“UTC eliminates all scheduling requirements.”What does AT TIME ZONE do?13 — Date and Time
IQ029UUID vs bigint primary key?Bigint is compact/ordered/central sequence; UUID supports decentralized generation but is larger. UUIDv7 adds temporal ordering benefits.Choose based on distribution, size, privacy, locality, operations.“UUIDs never scale” or “bigint cannot scale.”What does PG18 uuidv7 add?14 — UUID
IQ030Why prefer identity columns over serial in new schemas?Identity is SQL-aligned DDL with clearer schema semantics; serial is a PostgreSQL pseudo-type creating a sequence/default.Both use sequences but differ in DDL identity semantics.“serial is a real integer subtype.”ALWAYS vs BY DEFAULT?41 — Sequences and IDs
IQ031Why are sequences not gapless?Values can be consumed by rollbacks, cache, crashes, and concurrent allocation.Sequences optimize unique concurrent allocation, not accounting continuity.“ROLLBACK returns the number.”How design legally gapless numbering?41 — Sequences and IDs
IQ032JSON vs JSONB?json preserves input text representation; jsonb stores parsed binary form with richer operators/indexing and normalized object semantics.jsonb is usually query-oriented, but has write/storage trade-offs.“JSONB is always smaller/faster for everything.”When is json preferred?16 — JSON/JSONB
IQ033When is JSONB an anti-pattern?When stable relational facts, keys, common filters, and invariants are buried in an untyped document.You lose straightforward constraints/FKs/stats/discoverability and may amplify writes.“JSONB replaces normalization.”What belongs in JSONB?16 — JSON/JSONB
IQ034When use PostgreSQL arrays?Small row-owned homogeneous collections without independent relational lifecycle can fit arrays.Normalize when elements need FKs/metadata/independent updates.“Arrays are always denormalization and forbidden.”How index arrays?15 — Arrays
IQ035What are range types useful for?Intervals with operators for overlap/containment/bounds; ideal for scheduling/effective periods.Range semantics are safer than duplicated boundary logic.“Just two timestamps with nicer syntax.”Why use [) bounds?17 — Range Types
IQ036What is an exclusion constraint?A constraint preventing rows whose indexed operator relationships conflict, e.g. same room and overlapping range.Enforces concurrency-safe non-overlap invariants.“A CHECK that compares all rows.”Which index method commonly supports ranges?42 — Constraints
IQ037Normalization: what problem does 3NF address?Non-key facts should not depend transitively on other non-key facts; reduce anomalies/duplicate facts.Normalization organizes dependencies and sources of truth.“3NF means every table has three columns.”What is BCNF?45 — Normalization
IQ038When denormalize?After identifying normalized source of truth and measuring a read need, with explicit consistency/update strategy.Every duplicate creates synchronization cost.“Denormalize early for speed.”Give a safe derived read model.46 — Denormalization
IQ039Natural vs surrogate key?Natural uses stable domain identity; surrogate introduces technical identity while business candidate keys still need uniqueness.Stability/width/evolution/relationships matter.“Surrogate keys remove need for unique business rules.”Give a good natural key.43 — Primary Keys
IQ040Composite primary key: when useful?When identity is naturally scoped by multiple attributes, such as (order_id,line_no) or (tenant_id,id).It can directly enforce scope, but makes FKs wider.“Composite keys are always bad for ORMs.”Composite FK consequence?43 — Primary Keys
IQ041Why index child foreign-key columns?Parent update/delete checks and common joins can otherwise scan the child table; PostgreSQL does not auto-create child FK indexes.FK correctness and performance are separate.“The FK automatically creates both indexes.”When might you skip it?44 — Foreign Keys
IQ042CASCADE vs RESTRICT?CASCADE propagates lifecycle changes; RESTRICT/NO ACTION prevent parent change under defined timing semantics.Choose based on ownership, not convenience.“CASCADE is always easier.”NO ACTION vs RESTRICT nuance?44 — Foreign Keys
IQ043Deferrable constraint: why use it?Allows selected constraints to be checked later, often at COMMIT, so intermediate state may violate but final state is valid.Useful for swaps/cycles/batch transformations.“It disables the constraint.”How set deferred?42 — Constraints
IQ044What is NOT VALID useful for?Add supported constraints while avoiding immediate historical scan, then validate separately. New relevant writes are still checked as documented.Important zero-downtime migration pattern.“Constraint does nothing until validation.”Which constraints support it?126 — Zero-Downtime Migrations
IQ045Partial index: what is it?An index containing only rows satisfying a predicate.Great for stable small hot subsets and scoped uniqueness.“An index with only some columns.”Planner requirement for using it?57 — Advanced Index Design
IQ046Expression index: what is it?Index stores result of an expression, e.g. lower(email).Query predicates can use indexed transformed semantics.“A computed column is always required.”How enforce case-insensitive uniqueness?57 — Advanced Index Design
IQ047Covering index / INCLUDE?Key columns drive search/order; INCLUDE stores payload columns that can satisfy output without making them key order.Can enable index-only scans but increases index cost.“Included columns participate in ordering like keys.”Why may heap still be visited?57 — Advanced Index Design
IQ048Why can an index-only scan still fetch heap pages?PostgreSQL must verify tuple visibility unless the visibility map marks the heap page all-visible.Index stores data, but MVCC visibility belongs to heap/VM state.“If every SELECT column is indexed, heap fetches are zero.”What sets all-visible bits?57 — Advanced Index Design
IQ049B-tree vs GIN?B-tree suits scalar equality/range/order; GIN is inverted, suited to multi-element values like JSONB, arrays, FTS.Access method must match operators/data.“GIN is a faster B-tree.”GIN write trade-off?53 — GIN Indexes
IQ050When is BRIN useful?Very large tables where indexed values correlate with physical page order, e.g. append-time data.Compact block-range summaries can skip large regions.“BRIN gives exact O(log n) lookups.”When does it perform poorly?56 — BRIN
IQ051What is HOT update?Heap-Only Tuple update avoiding new index entries when indexed values are unchanged and same page has room.Reduces index/WAL churn.“An in-place row update.”How can extra indexes reduce HOT?77 — HOT Updates
IQ052What is fillfactor?Table/index storage setting leaving free page space to influence update/page-split behavior.Lower table fillfactor can improve same-page HOT chances.“Memory cache percentage.”Trade-off of lower fillfactor?77 — HOT Updates
IQ053Seq Scan vs Index Scan?Seq Scan reads table pages sequentially; Index Scan uses index entries then heap visits. Cheapest choice depends on rows/table/cache/correlation.Index is not automatically cheaper.“Index Scan is always better.”What if 80% of rows match?71 — Plan Nodes
IQ054Bitmap Heap Scan: why exists?Combines many matching tuple locations into page-oriented bitmap visits, often efficient for medium selectivity.Reduces random heap access and can combine indexes.“It scans the entire table like Seq Scan.”What is Bitmap Index Scan?71 — Plan Nodes
IQ055Nested Loop: when good?Small/selective outer input with cheap inner lookup, often indexed.Repeated inner work is efficient only when outer count is controlled.“Always best for joins with an index.”What if outer estimate is wrong by 1000×?72 — Join Algorithms
IQ056Hash Join: when good?Equality joins over substantial unsorted inputs when building/probing a hash table is efficient.Memory/batching/build side matter.“Can join any inequality efficiently.”What happens if hash spills?72 — Join Algorithms
IQ057Merge Join: when good?Inputs available/sortable by join keys, especially large ordered equality/range-compatible cases.It advances through sorted streams.“Same as sorting final output.”How can indexes avoid sort?72 — Join Algorithms
IQ058EXPLAIN cost means milliseconds?No; cost is a planner-relative unit from configured CPU/I/O estimates.Compare candidate plans, not wall-clock directly.“cost=100 means 100 ms.”What is startup vs total cost?70 — EXPLAIN
IQ059What do rows and loops mean in EXPLAIN ANALYZE?Rows are per-loop estimates/actual node output; loops tells executions, so total processed can multiply.Prevents underestimating nested work.“Rows is total across all loops.”100 rows × 1000 loops?70 — EXPLAIN
IQ060What does BUFFERS add to EXPLAIN?Shared/local/temp buffer hits, reads, dirties/writes, helping quantify data-page work.Distinguishes row-processing from I/O/cache patterns.“CPU profiling.”What does WAL option show?70 — EXPLAIN
IQ061Why can statistics go stale?Data volume/distribution changes between ANALYZE runs; autovacuum analyze thresholds may lag certain workloads.Planner estimates depend on sampled stats.“Planner reads every table before planning.”What does ANALYZE collect?73 — Query Statistics
IQ062What are extended statistics?Cross-column statistics such as dependencies, ndistinct, and multivariate MCVs.Fix independence-assumption errors for correlated predicates.“More index statistics.”Example country/city?73 — Query Statistics
IQ063What is a savepoint?A marker inside a transaction to roll back part of work without aborting the whole transaction.It provides partial recovery, not independent nested commit.“A nested transaction that can commit independently.”ROLLBACK TO effect?60 — Savepoints
IQ064Lost update: what is it?Concurrent logic causes one intended update to overwrite/negate another without preserving both effects.Often stems from read-modify-write application patterns.“Any two UPDATEs on same row.” PostgreSQL may serialize row writes safely, but app logic can still lose intent.Safer counter update?63 — Isolation
IQ065Optimistic vs pessimistic concurrency?Optimistic detects conflicts (e.g. version column); pessimistic locks before multi-step work.Choose by contention and decision shape.“Optimistic means no DB constraints.”Show versioned UPDATE.67 — Concurrency Patterns
IQ066SKIP LOCKED: when appropriate?Worker-queue style processing where skipping currently claimed rows is intended.It produces an intentionally incomplete view.“Use it on all SELECTs to avoid latency.”Why wrong for account report?64 — Locking
IQ067NOWAIT: what does it do?Fails immediately instead of waiting for a requested lock.Supports fail-fast workflows.“Skips locked rows.” That is SKIP LOCKED.NOWAIT vs lock_timeout?64 — Locking
IQ068How does PostgreSQL handle a deadlock?Detects wait-cycle and aborts one transaction so progress can resume.The application must rollback/retry as appropriate.“Database waits forever.”Best prevention pattern?65 — Deadlocks
IQ069Read Committed snapshot behavior?Each statement sees a snapshot including rows committed before that statement begins plus own changes.Repeated SELECTs may see new committed rows.“One snapshot for whole transaction.”Which level gives stable snapshot?63 — Isolation
IQ070Repeatable Read in PostgreSQL?Snapshot isolation with a stable transaction snapshot; prevents more than SQL minimum but can allow write skew.It is not fully serializable.“It locks every row read.”Give write-skew example.63 — Isolation
IQ071Serializable in PostgreSQL?SSI provides serializable outcomes by detecting dangerous dependencies and aborting transactions when needed.Application must retry whole transaction on serialization failure.“It runs one transaction at a time.”SQLSTATE for serialization failure?66 — Serializable Transactions
IQ072Why retry entire serializable transaction?Earlier reads influenced later decisions, so retrying only the failed statement may use stale assumptions.Transaction semantics are one decision unit.“Retry COMMIT only.”How handle external side effects?66 — Serializable Transactions
IQ073What is idle in transaction and why dangerous?Session has an open transaction but no active statement; it can hold locks/snapshot horizons and block vacuum/DDL.Idle does not mean harmless.“It consumes only a connection.”Which timeout helps?110 — Long Transactions
IQ074VACUUM vs VACUUM FULL?Normal VACUUM marks space reusable with light locks; FULL rewrites table, can return space to OS, needs strong exclusive lock.Different operational purpose.“FULL is a better routine vacuum.”When consider FULL?75 — VACUUM
IQ075Why can long transactions cause bloat?Old snapshots keep obsolete tuple versions potentially visible, so vacuum cannot reclaim them.MVCC cleanup horizon is global to relevant snapshots.“Because transaction logs get larger only.”What is xmin horizon concept?110 — Long Transactions
IQ076Physical vs logical backup?Physical copies cluster storage for binary recovery/PITR; logical dumps schema/data SQL-level representation with selective portability.Restore method/RPO/RTO/version needs differ.“Logical is always safer.”What does pg_dump produce?85 — Backups
IQ077What is PITR?Restore a base backup then replay archived WAL to a target time/LSN/transaction/timeline.Recovers to before logical accidents within retention.“Restore a SQL dump from yesterday only.”What is a timeline?87 — PITR
IQ078Sync vs async streaming replication?Async primary commits without standby ack; sync waits for configured standby acknowledgement, trading latency/availability for stronger RPO.Replication policy changes commit dependency.“Synchronous means zero downtime.”What happens if sync standby unavailable?88 — Streaming Replication
IQ079What is Row Level Security?Table policies that filter/validate rows based on role/session expressions via USING/WITH CHECK.Adds database-enforced row isolation.“A replacement for authentication.”Who can bypass RLS?96 — RLS
IQ080Why is search_path security-sensitive?Unqualified names resolve through schemas in order; writable early schemas can shadow intended objects, especially in elevated functions.Name resolution becomes part of trust boundary.“It only affects convenience.”How harden SECURITY DEFINER?07 — Schemas and Search Path