PostgreSQL & MySQL Query Plan Visualizer
Deconstruct complex relational query execution plans into interactive visual DAG trees. Diagnose unindexed sequential scans, memory sort spills to disk, cold buffer reads, and cardinality estimation errors with automated production DDL index recommendations.
Select an Architectural Query Plan Scenario
A high-frequency customer portal query executes a full table heap scan across 2,500,000 tuples because no compound index exists on (customer_id, status, created_at). 2,499,950 tuples are evaluated and discarded in memory, causing 35,210 cold storage read blocks and 842ms latency.
Seq Scan
((orders.status = 'PENDING'::text) AND (orders.customer_id = 94812))Full table scan inspected 2,500,000 planned rows and discarded 2,499,900 rows via filter predicate.
Planner expected 2,500,000 rows but execution yielded 100 rows.
Operation required 35,210 physical disk block reads vs only 412 RAM buffer hits.
Anatomy of Relational Query Optimizers: Cost Models & Plan Generation
In relational database management systems such as PostgreSQL and MySQL, SQL statements are declarative: they express what data the application requires, not the imperative physical algorithms or storage access paths required to retrieve it. The database Query Optimizer acts as a specialized compilation engine that converts the abstract syntax tree (AST) into a concrete physical execution plan.
The PostgreSQL Cost-Based Optimizer (CBO) utilizes a cost model derived from System R dynamic programming, calculating an abstract metric known as “cost units” (where 1.0 unit typically represents the cost of fetching a single 8kB page sequentially from disk). The total cost of an operator is computed via the fundamental formula:
Default PostgreSQL configuration assigns seq_page_cost = 1.0 and random_page_cost = 4.0. The ratio 4.0:1.0 was originally calibrated for legacy magnetic rotational hard drives, where physical disk head movement across platters incurred a massive 10ms mechanical seek penalty compared to contiguous sector streaming. On modern NVMe SSD storage infrastructures operating over PCIe 4.0/5.0 bus architectures, random access read latency is virtually identical to sequential throughput (~50 to 80 microseconds). Consequently, leaving random_page_cost at 4.0 causes the optimizer to irrationally avoid B-Tree index scans and Index Only Scans in favor of expensive sequential table scans. Database architects should calibrate random_page_cost = 1.1 or 1.25 on modern SSD cloud storage (AWS EBS gp3/io2, Google Cloud Hyperdisk, or bare-metal NVMe arrays).
In MySQL 8.0+, the optimizer incorporates both the classic Range & Join Optimizer and the modern Hypergraph Optimizer. The Hypergraph architecture models joins and predicates as nodes and edges in a hypergraph, enabling dynamic programming and genetic partition searches across complex multi-table joins without being constrained by left-deep tree assumptions.
Deconstructing Physical Access Paths: Seq Scan vs Index Scan vs Index Only Scan
When an engine accesses tuples within a relation, it selects from four fundamental physical access path operators, each representing distinct memory and storage I/O trade-offs:
Sequential Scan (Seq Scan)
Reads every physical 8kB page from the relation heap on disk sequentially into shared buffers. While efficient for scanning > 20% of a table via POSIX read-ahead prefetching, executing a Seq Scan on tables with millions of rows to return a handful of tuples is a primary cause of CPU exhaustion and cache pollution.
Index Scan
Traverses B-Tree internal nodes from root to leaf to retrieve item pointers (TIDs). For each matching TID, it performs an immediate random I/O fetch against the table heap page to extract remaining tuple columns and verify MVCC snapshot visibility.
Index Only Scan
The gold standard of query execution. Occurs when all projected and filtered columns exist within the index (or INCLUDE clause). By consulting the table Visibility Map (VM), if the page is marked all-visible, the engine eliminates heap visits entirely, delivering sub-millisecond responses.
Bitmap Heap Scan
Employs a two-tier mechanism: the Bitmap Index Scan evaluates matching TIDs and marks them in a memory bitmap structured by physical block number. The Bitmap Heap Scan then reads target pages sequentially, combining multiple index lookups (BitmapAnd / BitmapOr) seamlessly.
Relational Join Mechanics: Nested Loop, Hash Join, and Merge Join
Nested Loop Join
Evaluates each row of the outer relation and invokes an inner scan (typically an indexed seek) for each outer row.
Best For: Small outer sets (< 1,000 rows) with indexed inner keys. Catastrophic when outer sets are large.
Hash Join
Builds an in-memory hash table over the smaller relation using the join attribute as the hash key, then streams the larger table to probe matches.
Best For: Large unsorted datasets with equality predicates. Spills to multi-batch disk runs if hash table > work_mem.
Merge Join
Requires both inputs to be sorted by the join key. Advances parallel cursors across both sorted relations in a single synchronized linear sweep.
Best For: Inputs already ordered by B-Tree indexes or queries with massive data streams and low memory footprints.
Parallel Query Execution Architecture: Gather & Dynamic Shared Memory
For analytical workloads scanning millions of records, modern relational engines leverage intra-query parallelism. In PostgreSQL, parallel query execution is orchestrated via the Gather or Gather Merge node.
The query coordinator process creates a Dynamic Shared Memory (DSM) segment and spawns background worker processes governed by max_parallel_workers_per_gather. Physical heap blocks are dynamically partitioned among workers using atomic block counters. Each worker executes a Parallel Seq Scan or Parallel Index Scan, computes partial aggregations or hash joins independently, and transmits serialized result tuples across DSM ring buffers back to the leader process.
While parallel queries can reduce wall-clock execution time by 3× to 8×, they introduce inter-process synchronization latency (represented by parallel_setup_cost) and worker memory contention. In high-concurrency OLTP applications with hundreds of simultaneous transactions per second, unconstrained parallel query execution can quickly deplete CPU cores, leading to thread context-switch thrashing and cascading tail-latency degradation.
The Cardinality Estimation Trap: How Stale Statistics Wreck Plans
The optimizer does not execute queries to determine costs; it relies entirely on statistical profiles collected by the background ANALYZE process into the system catalog view pg_stats. These profiles include:
When a table experiences rapid bulk insertions, deletions, or data skew, histograms become stale. If the planner estimates that a join will produce 10 rows when it actually produces 250,000 rows, this 25,000× error cascades through subsequent join operators. The optimizer picks an inner Nested Loop join rather than a Hash Join, resulting in catastrophic database lock contention, memory exhaustion, and connection pool starvation.
Furthermore, standard single-column statistics assume statistical independence across attributes. When attributes are tightly coupled (for example, make = 'Toyota' AND model = 'Corolla'), the optimizer multiplies independent selectivity factors, yielding a fraction of the actual row count. PostgreSQL resolves this via Extended Statistics:
ANALYZE vehicles;
Memory Sizing & Disk Spills: work_mem, Buffers, and External Merge Sorts
In PostgreSQL, sorting operations (ORDER BY, DISTINCT, window functions) and hashing operations (Hash Join, HashAggregate) require scratchpad RAM governed by the work_mem configuration parameter.
When an in-memory quicksort or hash bucket exceeds work_mem, the query execution engine does not fail—instead, it silently falls back to an external merge sort. Intermediate sorted tuple chunks are serialized to disk temporary files inside the pgsql_tmp directory. These runs are iteratively read back and merged, replacing microsecond memory bus operations with millisecond storage I/O and creating massive spikes in Temp Written Blocks and Temp Read Blocks.
| Metric in EXPLAIN BUFFERS | Physical Storage Meaning | Target SLA / Threshold |
|---|---|---|
| Shared Hit Blocks | 8kB pages found directly in shared_buffers RAM | > 95% of all blocks for OLTP workloads |
| Shared Read Blocks | 8kB pages read from OS file cache or NVMe physical storage | Zero or minimal for point lookups; bounded for reporting |
| Temp Written / Read | Scratchpad blocks written to disk due to work_mem exhaustion | 0 blocks (must fit completely in RAM) |
Relational Anti-Pattern Hall of Fame: Why Valid Indexes Get Ignored
Implicit Type Casting
Querying WHERE phone_number = 1234567890 when phone_number is stored as VARCHAR forces the engine to apply an implicit functional cast CAST(phone_number AS bigint) to every row in the table, completely blinding the B-Tree index.
Non-Sargable Expressions
Filtering on WHERE date_trunc('day', created_at) = '2026-01-01' wraps the index column in a scalar function. Rewrite as a sargable range seek: WHERE created_at >= '2026-01-01' AND created_at < '2026-01-02'.
Deep OFFSET Pagination
Executing LIMIT 50 OFFSET 100000 forces the query engine to read, sort, and discard 100,000 tuples before returning 50. Replace with Keyset Cursor pagination: WHERE id > :last_seen_id ORDER BY id LIMIT 50 for O(1) performance.
Production Query Optimization Playbook: From Diagnosis to Remediation
Covering Indexes with INCLUDE
Add non-search payload columns to the INCLUDE clause instead of index keys: CREATE INDEX idx ON orders (customer_id, status) INCLUDE (total_amount);. This enables pure Index Only Scans without enlarging B-Tree search branching factor.
Partial Indexes for Skewed States
If 98% of orders are ‘DELIVERED’ and only 2% are ‘PENDING’, index only the active subset: CREATE INDEX idx_pending ON orders (created_at) WHERE status = 'PENDING';. Shrinks index memory by 95% and eliminates write amplification.
Always Index Foreign Keys
Relational engines do not automatically index foreign key columns. Unindexed foreign keys turn parent record updates or child table joins into full sequential sweeps, causing catastrophic table-level lock contention.
Database Query Plan Architecture FAQs
What is the architectural difference between an Index Scan, Index Only Scan, and Bitmap Heap Scan in PostgreSQL?
An Index Scan traverses a B-Tree index from root to leaf to locate matching tuple identifiers (TIDs), and immediately performs a random I/O read on the underlying table heap to fetch each row. An Index Only Scan occurs when all projected columns and filter predicates exist inside the index leaf pages (or are included via the INCLUDE clause); if the table's Visibility Map confirms that the target heap page contains no dead tuples from concurrent transactions, the engine skips heap access entirely (Heap Fetches: 0), retrieving tuples at pure RAM buffer speed. A Bitmap Heap Scan is a two-phase retrieval used when a query matches multiple rows spread across many pages: first, a Bitmap Index Scan evaluates index entries and builds a structured bitmap of target physical heap blocks in work_mem; second, the Bitmap Heap Scan sorts these page pointers in physical disk storage order and visits each page sequentially. This transforms random storage seeks into sequential read-ahead I/O, dramatically reducing disk head movement and NVMe read queue latency.
Why does a low planner cost sometimes disguise a catastrophically slow query execution?
The PostgreSQL Cost-Based Optimizer computes total cost prior to execution based on statistical distributions stored in pg_statistic (such as Most Common Values lists and equi-depth histogram bounds). If these statistics are outdated or if columns have strong real-world correlations that violate the optimizer's independent probability assumption, the planner will severely underestimate the actual row count. For example, if the planner predicts a filter will return 15 rows instead of 450,000 rows, it will choose a Nested Loop join because 15 index lookups on the inner table carry a deceptively low estimated cost of ~45. In reality, the inner index scan executes 450,000 times, causing 450,000 individual index traversals and hundreds of megabytes of random disk reads. In this scenario, execution time explodes from milliseconds to tens of seconds, while the static cost metric remains frozen at a negligible number.
How does work_mem govern in-memory sorting vs external merge disk spills, and why should it not be globally inflated?
PostgreSQL allocates work_mem on a per-operation, per-backend basis rather than a global cap. If a sorting operation (ORDER BY), hash aggregation (GROUP BY), or hash join exceeds the allocated work_mem, PostgreSQL terminates in-memory quicksort and spills intermediate sorted runs onto temporary disk files. These runs are later merged via an external merge sort, incurring massive disk write and read penalties (visible as Temp Written Blocks in EXPLAIN BUFFERS). However, globally increasing work_mem to an aggressive value (such as 1GB) is dangerous: a single complex reporting query featuring 4 sorts, 2 hash joins, and 4 parallel worker threads can allocate work_mem across 24 concurrent slots. If 50 web connections execute such queries simultaneously, memory consumption can quickly exceed physical RAM, triggering the Linux kernel Out-Of-Memory (OOM) killer to terminate the PostgreSQL postmaster process. Best practice mandates keeping global work_mem modest (16MB to 64MB) and using 'SET LOCAL work_mem = 256MB' inside specific analytical sessions or batch jobs.
What is the leftmost prefix rule in composite B-Tree indexes, and how does it dictate predicate selectivity?
B-Tree indexes maintain composite keys (ColumnA, ColumnB, ColumnC) in strict lexicographical sorted sequence: sorted primarily by ColumnA, then by ColumnB within matching ColumnA values, and finally by ColumnC. Because of this hierarchical ordering, the database engine can only use index seek operations for queries that constrain leading contiguous columns starting from the leftmost position. Equality filters on (ColumnA = 10 AND ColumnB = 'ACTIVE') allow direct root-to-leaf traversal. However, if a query filters on ColumnB alone without specifying ColumnA, the engine cannot navigate the tree directly and must either perform a Full Index Scan or revert to a full table Sequential Scan. Furthermore, when an inequality or range predicate is evaluated (such as ColumnA = 10 AND ColumnB > 50 AND ColumnC = 'PAID'), the index seek terminates at ColumnB; ColumnC cannot be used for boundary range reduction and serves only as a residual filter.
How do shared buffer hits and physical disk reads affect p99 database latency on modern NVMe storage?
In relational storage engines like PostgreSQL, tables and indexes are divided into fixed 8kB memory pages. A Shared Buffer Hit occurs when the requested page is already resident in the database shared_buffers cache in RAM; this access completes over the CPU memory bus in approximately 100 nanoseconds. A Shared Buffer Read occurs when the page is not in shared_buffers, requiring a system call to the operating system kernel cache or an asynchronous NVMe PCIe read operation, taking 50 to 150 microseconds (and 5 to 10 milliseconds on legacy rotational media or throttled cloud block storage). When a sequential scan or unindexed join processes 50,000 cold blocks from disk, the query incurs 50,000 * 100us = 5,000 milliseconds of physical I/O wait time. Enabling 'track_io_timing = on' in PostgreSQL allows EXPLAIN (ANALYZE, BUFFERS) to explicitly report 'I/O Timings: read=4820ms', distinguishing CPU-bound computational bottlenecks from storage-bound I/O bottlenecks.
When does PostgreSQL choose a Hash Join over a Merge Join or Nested Loop Join?
PostgreSQL evaluates three distinct join strategies based on row counts, available memory, indexes, and join predicates. A Nested Loop Join is chosen when the outer table produces very few rows (e.g. < 100) and the inner table possesses an index on the join key; it loops through the outer rows and executes an index seek on the inner table for each match. A Hash Join is preferred for large, unsorted datasets joined on equality operators (A.id = B.a_id): the optimizer scans the smaller input relation, constructs an in-memory hash table in work_mem using a hashing function on the join key, and then streams the larger probe table through the hash table in a single sequential pass. A Merge Join requires both inputs to be sorted on the join keys; if both relations are already indexed on the join columns or if pre-sorting cost is modest, Merge Join performs a simultaneous linear scan across both sorted streams, making it exceptionally fast for massive datasets and streaming joins.