dataiotech Labs
PILLAR GUIDE · PERFORMANCE & QUERY OPTIMIZATION

Performance & Query Optimization

Resolving database performance bottlenecks in PostgreSQL, MySQL, and modern systems through telemetry and measurement rather than guesswork.

Senior DBA / SRE / Staff EngineerRead Time: 28 minUpdated: Nov 2026Scope: PostgreSQL 16 / 17, MySQL 8.4 LTS, SQL Server 2022
What is a Pillar? (Content Architecture)

In brief: The core, foundational guide for a subject. On dbaguide.com, content is organized into 2 architectural tiers:

1. Pillar (Core Guide)

The comprehensive, evergreen guide covering the full scope of a topic. It serves as an architectural roadmap showing how to diagnose performance, the 4-layer hierarchy, and how specialized topics connect.

2. Cluster (Deep-Dive Guides)

Specialized, single-topic guides unpacking each sub-discipline in depth (pg_stat_statements, N+1 problem, autovacuum tuning, explain analyze, memory tuning, lock triage). Every cluster connects back to the pillar, and the pillar links to all clusters.

Why This Model? (Pillar & Cluster Architecture)
        [ PILLAR ]
     Performance & Query
       Optimization
       /    |    \
      /     |     \
 [Cluster] [Cluster] [Cluster]
 Metrics   N+1     Vacuum
  • 1. For Readers:Start with the comprehensive pillar roadmap, then drill into specialized clusters without losing context.
  • 2. For SEO:Search engines reward comprehensive topical authority. Interlinked pillar-cluster structures represent the highest quality graph.
  • 3. For Engineering:Plan the holistic domain once, then engineer focused execution guides without repetitive boilerplate.
Simple analogy: Pillar = Table of contents + Overview chapter · Cluster = Dedicated technical chapters
What This Pillar Covers

In production, database performance degradation is rarely an isolated slow query. The operational incident chain is predictable:

The Incident Chain:
Bad Plan→Excessive I/O→Buffer Pool Pressure→Lock Contention→Pool Saturation→App Timeout
This pillar is engineered to reverse that chain:

1. Measure First · 2. Diagnose with Telemetry · 3. Modify with Validation. Never change a configuration, index, or query without establishing a baseline.

60-Second Performance Triage

The first 5 telemetry checkpoints to examine during a performance incident (Telemetry over guesswork).

1. What is running right now? (Active Sessions & Wait Events)

Long-running sessions with active wait events are the primary suspects.

SELECT pid, usename, application_name, state, wait_event_type, wait_event,
       now() - query_start AS duration, left(query, 120) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY query_start;

2. Are there active locks? (Blocking & Blocked Chain)

Instantly identify which PID is waiting on which blocking PID.

SELECT blocked.pid AS blocked_pid,
       blocking.pid AS blocking_pid,
       blocked.query AS blocked_query,
       blocking.query AS blocking_query
FROM pg_stat_activity blocked
JOIN pg_locks blocked_lock ON blocked.pid = blocked_lock.pid
JOIN pg_locks blocking_lock
  ON blocking_lock.locktype = blocked_lock.locktype
 AND blocking_lock.granted
JOIN pg_stat_activity blocking ON blocking.pid = blocking_lock.pid
WHERE NOT blocked_lock.granted;

3. What are the most expensive queries? (pg_stat_statements)

Top queries consuming cumulative system CPU and disk execution time.

SELECT query, calls, total_exec_time, mean_exec_time, rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

4. Is there buffer cache pressure? (Cache Hit Ratio)

If cache hit ratio drops below 99%, audit memory allocations and index usage.

SELECT datname, blks_hit, blks_read,
       round(100.0 * blks_hit / NULLIF(blks_hit + blks_read, 0), 2) AS cache_hit_ratio
FROM pg_stat_database;

5. Is the plan genuinely suboptimal? (EXPLAIN ANALYZE + BUFFERS)

Inspect actual execution duration and disk buffer hits rather than optimizer estimates.

EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM orders WHERE customer_id = 123 AND status = 'open';

The 4 Layers of Database Performance

Hierarchy flows strictly from Layer 1 down to Layer 4. Hardware upgrades and parameters never compensate for a bad query plan.

LAYER 1PRIORITY #1

Layer 1: Query & Execution Plan

Most common root causes:

  • Missing or suboptimal index
  • Suboptimal join order
  • SELECT * with wide row overhead
  • Function wrapping indexed WHERE column
  • Outdated catalog statistics
  • N+1 query loops
Rule: Fix the query plan first. Hardware upgrades and parameter tuning never rescue a flawed plan.
LAYER 2ACCESS PATHS

Layer 2: Indexing & Access Paths

Access PathWhen Optimal?When Inefficient?
Seq ScanSmall tables, large percentage of table scannedSingle row filtered across millions of rows
Index ScanHigh selectivity (small row subset)Excessive random I/O on cold buffers
Index Only ScanAll queried columns covered by indexDirty Visibility Map triggers heap fetches
Bitmap Heap ScanModerate selectivity with multiple pagesRedundant overhead on unique key lookups
BRINNaturally correlated physical append logsRandomly dispersed non-sequential data

PostgreSQL Index Type Selection

  • B-Tree: Default, equality + range scans
  • Hash: Strict equality lookups only
  • GiST: Geometric, spatial, range types
  • GIN: JSONB, arrays, full-text search
  • BRIN: Massive append-only time series

MySQL / InnoDB Architectural Note

Clustered index equals Primary Key. Suboptimal PK selection bloats all secondary indexes because each secondary index leaf node stores the full Primary Key value rather than a physical tuple pointer.

LAYER 3MEMORY & I/O

Layer 3: Memory, I/O & Vacuuming

PostgreSQL Baseline Mental Model

  • shared_buffers: 25% of total system RAM
  • effective_cache_size: 75% of total system RAM
  • work_mem: Per operation/sort, scale conservatively
  • maintenance_work_mem: High allocation for vacuum & index builds

MySQL / InnoDB Baseline Model

  • innodb_buffer_pool_size: 70-80% of total system RAM
  • innodb_redo_log_capacity: Tune for sustained write spikes
  • innodb_flush_method: O_DIRECT on Linux production hosts
Autovacuum Invariant: Delayed vacuuming triggers table bloat, index bloat, stale stats, and query degradation.
SELECT relname, n_dead_tup, last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;
n_dead_tup monotonically growing indicates autovacuum thresholds are falling behind write volume.
LAYER 4LOCKS & CONCURRENCY

Layer 4: Connection Pooling, Locks & Concurrency

Performance degradation is predominantly waiting rather than CPU saturation. The standard concurrency chain:

  1. Long-running transactions remain uncommitted
  2. Exclusive row/table locks are held
  3. Incoming queries queue up behind locks
  4. Connection pool reaches max saturation
  5. Application experiences cascading timeouts
PostgreSQL Check
SELECT pid, now() - xact_start AS xact_age, state, left(query, 100)
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY xact_start
LIMIT 20;
MySQL Check
SELECT trx_id, trx_state, trx_started, trx_query
FROM information_schema.innodb_trx
ORDER BY trx_started;
Golden Rule: Keep transactions short. Never perform external HTTP calls, sleep routines, or user I/O within a database transaction.
N+1 Query Anti-Pattern
Read Full Guide

The most insidious performance bottleneck. Each individual query runs in sub-milliseconds, but executing inside application loops multiplies into thousands of database round-trips.

Anti-Pattern (N+1 Loop)
// 1 query: fetch 100 users
users = db.query("SELECT * FROM users");

// 100 additional queries inside loop!
for u in users:
  orders = db.query(
    "SELECT * FROM orders WHERE user_id = ?", u.id
  )
Optimized (Batch / JOIN)
// Single query with JOIN
SELECT u.id, u.name, o.id, o.total
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;

// or inside ORM:
User.objects.prefetch_related('orders')

How to Prevent It?

  • • Enable ORM eager loading (select_related / includes)
  • • Project only required columns; avoid SELECT *
  • • Implement deterministic cursor / keyset pagination
Table Partitioning: When to Partition?

Partitioning does not automatically accelerate point queries; its primary value is isolating maintenance and pruning partitions.

Partition When:

  • Table is massive and queries naturally filter by timestamp or tenant key
  • Historical data is periodically pruned or archived by dropping partitions
  • Vacuum and index maintenance exceeds maintenance windows on monolithic tables

Do Not Partition When:

  • Queries omit partition keys (causing full partition fan-out across all shards)
  • Joins traverse non-partitioned foreign keys
  • Table data fits comfortably in buffer cache
PostgreSQL Example: Range Partitioning
CREATE TABLE orders (
  id bigint,
  created_at timestamptz NOT NULL,
  customer_id bigint,
  total numeric
) PARTITION BY RANGE (created_at);

CREATE TABLE orders_2026_11 PARTITION OF orders
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
Pre-Production Performance Verification Checklist
✓
Top 20 critical queries verified with EXPLAIN (ANALYZE, BUFFERS)
✓
pg_stat_statements / Performance Schema enabled and baseline established
✓
Missing indexes created; unused redundant indexes pruned
✓
Autovacuum & Analyze verified with zero dead tuple accumulation
✓
Connection pool capacity mathematically calculated against CPU cores
✓
Long-running transaction alerts configured with thresholds
✓
Slow query log enabled with appropriate log_min_duration_statement
✓
Load testing validated against full production data volumes
✓
Post-failover query plans and catalog stats verified on replicas

Cluster Guides in this Pillar

All cluster guides below are published with complete unabridged technical runbooks.

[PostgreSQL] RUNBOOKPUBLISHED

[PostgreSQL] RUNBOOK: Finding Top 20 Expensive Queries with pg_stat_statements

System CPU is saturated. This runbook identifies the top 20 queries by cumulative execution time, isolates the top 3 offenders, and directs remediation without premature hardware scaling.

PostgreSQL 16 / 17•18 dk
Read Guide
[Motor-Bağımsız] DEEP DIVEPUBLISHED

[Engine-Agnostic] DEEP DIVE: The N+1 Query Problem and Connection Pool Saturation

An individual query running in 8ms is harmless, but repeating it 10,000 times inside an application loop locks worker threads, exhausts connection pools, and inflates database latency. This guide covers detection and resolution.

PostgreSQL 16 / 17, MySQL 8.4 LTS•22 dk
Read Guide
[Motor-Bağımsız] CHEATSHEETPUBLISHED

[Engine-Agnostic] CHEATSHEET + GUIDE: Reading and Deconstructing EXPLAIN ANALYZE

EXPLAIN provides query planner estimates; EXPLAIN ANALYZE delivers ground truth telemetry. Deconstruct plan node trees, loops, actual rows vs estimated rows, and buffer memory hits.

PostgreSQL 16 / 17, MySQL 8.4 LTS•24 dk
Read Guide
[PostgreSQL] RUNBOOKPUBLISHED

[PostgreSQL] RUNBOOK + DEEP DIVE: Vacuum, Analyze, and Autovacuum Tuning

PostgreSQL MVCC generates dead row versions on every UPDATE and DELETE. Stale vacuum cycles trigger table and index bloat, stale statistics, and catastrophic transaction ID wraparound outages.

PostgreSQL 16 / 17•24 dk
Read Guide
[PostgreSQL] DEEP DIVEPUBLISHED

[PostgreSQL] DEEP DIVE: Index Architecture — B-Tree, Hash, GiST, GIN, BRIN Deep Dive

An improper index degrades write performance, consumes disk space, and misleads the query planner. Choose deliberately between B-Tree, Hash, GiST, GIN, and BRIN for specialized data layouts.

PostgreSQL 16 / 17•26 dk
Read Guide
[PostgreSQL] RUNBOOKPUBLISHED

[PostgreSQL] RUNBOOK: Memory Tuning — shared_buffers, work_mem, effective_cache_size

PostgreSQL memory architecture divides RAM between shared memory and per-operation client memory. Improper work_mem allocation triggers OOM killer events under concurrent load.

PostgreSQL 16 / 17•25 dk
Read Guide
[PostgreSQL] RUNBOOKPUBLISHED

[PostgreSQL] RUNBOOK: 5-Minute Lock Diagnostics via pg_locks and pg_stat_activity

Locks are insidious: CPU is low, disk is quiet, yet applications freeze. Identify blocking vs blocked PID trees within 5 minutes, execute safe terminations, and configure lock timeouts.

PostgreSQL 16 / 17•22 dk
Read Guide
[Motor-Bağımsız] GUIDEPUBLISHED

[Universal] GUIDE: Connection Pool Sizing — Formula and Real Life

Connection pooling is the most misconfigured part of database performance. Most teams assume a bigger pool means a faster system. The reality is the opposite: an oversized pool slows the database down. Every connection consumes memory, forces context switching, and increases lock contention. In this guide you will learn how to calculate the correct pool size, how to use application pools together with external poolers like PgBouncer / ProxySQL, how to diagnose a full pool, and how to choose safe production values.

PostgreSQL 16 / 17, MySQL 8.4 LTS, SQL Server 2022•24 dk
Read Guide
[Motor-Bağımsız] BLUEPRINTPUBLISHED

[Universal] BLUEPRINT: Partitioning — When to Split, When Not to Split

Partitioning is the most misunderstood medicine in the database world. Not every large table should be partitioned. Wrong partitioning slows the table instead of speeding it up, complicates queries, and makes maintenance harder. Correct partitioning makes even a billion-row table manageable. In this guide you will learn what partitioning is, the decision tree for when to split and when not to split, the 3 main partitioning types, the live migration plan, and the 7 most common mistakes. This article completes the Universal leg of the Performance Pillar.

PostgreSQL 16 / 17, MySQL 8.4 LTS, SQL Server 2022•26 dk
Read Guide
[MySQL] RUNBOOKPUBLISHED

[MySQL] RUNBOOK: Finding the 20 Most Expensive Queries with Performance Schema

What pg_stat_statements is in PostgreSQL, Performance Schema is in MySQL. When the system slows down, adding an index by guess or changing a parameter is forbidden. First we measure. In this guide you will learn how to enable Performance Schema, how to find the 20 most expensive queries by total time, how to diagnose the top 3 queries precisely, and how to decide the fix. This article is the first cluster that starts the MySQL leg of the Performance Pillar.

MySQL 8.4 LTS / 8.0•22 dk
Read Guide
[MySQL] RUNBOOKPUBLISHED

[MySQL] RUNBOOK: InnoDB Buffer Pool and Redo Log Tuning

What shared_buffers is in PostgreSQL, InnoDB Buffer Pool is in MySQL. If the Buffer Pool is small, every query goes to disk. If the Redo Log is small, write operations constantly suffer checkpoint pressure, and the system stutters. In this guide you will learn how to size the Buffer Pool correctly, how to tune the Redo Log for your write load, how to control flush behavior, and how to apply changes safely in production.

MySQL 8.4 LTS / 8.0•24 dk
Read Guide
[MySQL] DEEP DIVEPUBLISHED

[MySQL] DEEP DIVE: InnoDB Purge and Undo Tuning — The MySQL Counterpart of Vacuum

If Vacuum lags in PostgreSQL, the table bloats. If Purge lags in MySQL, Undo bloats. The result is the same: The table grows, queries slow down, disk fills up, and worst of all the system stalls because of a long transaction. In this guide you will learn InnoDB's MVCC model, how the Purge mechanism works, why Undo tablespace grows, what History List Length means, and how to keep Purge healthy in production.

MySQL 8.4 LTS / 8.0•24 dk
Read Guide
[MySQL] RUNBOOKPUBLISHED

[MySQL] RUNBOOK: Lock Diagnosis — InnoDB Lock Waits in 5 Minutes

The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In this guide you will learn how to recognize a lock problem in MySQL, how to find blocking and blocked queries in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the MySQL leg of the Performance Pillar.

MySQL 8.4 LTS / 8.0•22 dk
Read Guide
[SQL Server] RUNBOOKPUBLISHED

[SQL Server] RUNBOOK: Finding the 20 Most Expensive Queries — Query Store + DMV

What pg_stat_statements is in PostgreSQL, what Performance Schema is in MySQL, Query Store + DMV is in SQL Server. When the system slows down, adding an index by guess or changing a parameter is forbidden. First we measure. In this guide you will learn how to enable Query Store, how to find the 20 most expensive queries by total time, how to diagnose the top 3 queries precisely, how to detect plan regression, and how to decide the fix. This article is the first cluster that starts the SQL Server leg of the Performance Pillar.

SQL Server 2022 / 2019•24 dk
Read Guide
[SQL Server] RUNBOOKPUBLISHED

[SQL Server] RUNBOOK: Memory Tuning — Buffer Pool and Memory Grant

What shared_buffers is in PostgreSQL, what InnoDB Buffer Pool is in MySQL, Buffer Pool is in SQL Server. But SQL Server has one difference: It does not leave memory to the OS, it manages it itself. Default setting is to use all memory. This looks good at first, but no room remains for the OS, the server swaps, the system slows down. In this guide you will learn how much memory to allocate to SQL Server, how the Buffer Pool works, how to diagnose Memory Grant pressure, how to choose MAXDOP and Cost Threshold correctly, and how to apply changes safely in production.

SQL Server 2022 / 2019•24 dk
Read Guide
[SQL Server] RUNBOOKPUBLISHED

[SQL Server] RUNBOOK: Lock Diagnosis — Blocking and Deadlock in 5 Minutes

The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In SQL Server this appears a bit differently than in other engines: With `LCK_M_` waits, blocking chain, and deadlock graph. In this guide you will learn how to recognize a lock problem in SQL Server, how to find blocking and blocked queries in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the SQL Server leg of the Performance Pillar.

SQL Server 2022 / 2019•22 dk
Read Guide
[Oracle] RUNBOOKPUBLISHED

[Oracle] RUNBOOK: Finding the 20 Most Expensive Queries — AWR + ASH

What pg_stat_statements is in PostgreSQL, what Performance Schema is in MySQL, what Query Store is in SQL Server, AWR + ASH is in Oracle. But Oracle has one difference: AWR is not only query statistics, it is the health report of the whole database. When the system slows down, adding an index by guess or changing a parameter is forbidden. First we measure. In this guide you will learn how AWR snapshots work, how to find the 20 most expensive queries by total time, how to diagnose the top 3 queries precisely, how to detect plan changes, and how to decide the fix. This article is the first cluster that starts the Oracle leg of the Performance Pillar.

Oracle 19c / 21c / 23ai•24 dk
Read Guide
[Oracle] RUNBOOKPUBLISHED

[Oracle] RUNBOOK: Memory Tuning — SGA and PGA

What shared_buffers is in PostgreSQL, what InnoDB Buffer Pool is in MySQL, what Buffer Pool is in SQL Server, SGA is in Oracle. But in Oracle memory is in two parts: SGA and PGA. SGA is memory shared by all sessions. PGA is each session's own memory. If one is small the system slows down, if the other is small queries fall to temp. In this guide you will learn how to share SGA and PGA correctly, how to interpret Buffer Cache hit ratio, how to diagnose PGA pressure, how to choose Automatic Memory Management settings correctly, and how to apply changes safely in production.

Oracle 19c / 21c / 23ai•24 dk
Read Guide
[Oracle] RUNBOOKPUBLISHED

[Oracle] RUNBOOK: Lock Diagnosis — Enqueue and Row Lock in 5 Minutes

The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In Oracle this appears a bit differently than in other engines: With `enq: TX - row lock contention` waiting, `V$LOCK` and `V$SESSION` chains. In this guide you will learn how to recognize a lock problem in Oracle, how to find blocking and blocked sessions in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the Oracle leg of the Performance Pillar and the whole Performance Pillar.

Oracle 19c / 21c / 23ai•22 dk
Read Guide
Next Step

Finding Top 20 Expensive Queries with pg_stat_statements

Because all database performance engineering starts with measurement, setting the stage for all remaining guides.

Open Runbook