Internals

Inside SQL Server 2022 — Launching the YouTube Series

2025-11-05 · 2 min

“Knowing that it works is not enough. You need to know why it works.” — SQLManiak


SQL Server is more than tables, indexes, and queries. It is a vast engine constantly bringing order to the chaos of data — writing, recovering, compressing, and managing every byte.

That is why a new series is launching: Inside SQL Server 2022 🎬. The project aims to reveal the inner workings of the engine — as the system sees them, rather than the administrator.

When Does SQL Server Compile a New Query Plan?

2025-11-03 · 2 min

SQL Server is clever. It does not compile a new plan for every execution — it does so when compilation is needed. Before executing a query, the engine checks the plan cache. If a suitable cached plan exists, it may reuse it.

🔍 When is a new plan created?

Compilation or recompilation may occur when:

🧠 How can you inspect this?

1
2
3
4
5
6
7
8
9
-- podejrzyj, ile planów trzyma SQL Server
SELECT COUNT(*) AS PlansInCache FROM sys.dm_exec_cached_plans;

-- zobacz najczęściej używane plany
SELECT TOP 10 usecounts, objtype, cacheobjtype, size_in_bytes / 1024 AS KB,
       DB_NAME(st.dbid) AS DatabaseName, st.text
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
ORDER BY usecounts DESC;

🧩 Why does it matter?

Frequent recompilation can consume unnecessary CPU. On the other hand, overly aggressive reuse can expose parameter sniffing problems. Balancing these behaviors is one of the keys to SQL Server performance.

THREADPOOL Waits: When SQL Server Runs Out of Workers

2025-10-31 · 3 min

SQL Server is like an organism that breathes through worker threads. Each worker is a breath; without them, the system suffocates.

When you see THREADPOOL in sys.dm_os_wait_stats, SQL Server may be struggling for air. This is not an ordinary wait: it can indicate that the engine cannot allocate additional workers because available threads are occupied by parallel tasks, blocking chains, or other work.


🔍 Inspect the DMV

1
2
3
4
-- sprawdź obciążenie puli wątków
SELECT scheduler_id, current_tasks_count, runnable_tasks_count, active_workers_count, work_queue_count
FROM sys.dm_os_schedulers
WHERE scheduler_id < 255;

📊 Interpretation:

HOBT: The Hierarchy of Data Organization

2025-10-30 · 6 min

Data in SQL Server does not lie around randomly. It forms structures whose branches lead to data pages. HOBT (Heap Or B-Tree) is the storage structure behind each B-tree index and heap table. It is the skeleton of data organization and addressing — from the root, through intermediate levels, down to the leaf pages of a B-tree.

“Structure is the form in which order exists.” — SQLManiak


🧩 What is a HOBT in practice?

Each partition of an index or heap has one HOBT (a table with one partition and three indexes has four HOBTs; a table with four partitions and two indexes has eight).

The ARIES Engine: How SQL Server Records Transaction History

2025-10-29 · 3 min

SQL Server does not forget. Before modified data pages are written to disk, the engine records the history of what has changed. This is the foundation of ARIES (Algorithm for Recovery and Isolation Exploiting Semantics), a key part of reliable transaction processing.

“History is a system’s memory.” — SQLManiak


⚙️ Write-Ahead Logging (WAL)

Every modification in SQL Server is represented in the transaction log (.ldf):

  1. A log record describing the change is created, identified by an LSN (Log Sequence Number).
  2. The log record is flushed to durable storage.
  3. Only then may the modified data page be written to disk.

This is Write-Ahead Logging (WAL): log first, data page later. It allows SQL Server to recover after a failure.

TempDB: SQL Server's Playground

2025-10-28 · 2 min

TempDB is SQL Server’s laboratory. Temporary tables, sorts, worktables, spools, hash operations, and row versions used by snapshot isolation may all rely on it. If the database is the mind, TempDB is its workshop.

An overloaded TempDB slows down the whole system, like a workbench that is too small for the job.

⚙️ What goes into TempDB?

🧠 TempDB architecture

TempDB is shared by the entire SQL Server instance and is recreated when the instance starts.

Parameter Sensitive Plan: SQL Server's Context-Aware Intelligence

2025-10-27 · 2 min

Every execution plan is a decision about how to get from data to a result. For years, SQL Server could cache a plan optimized for an initial parameter value (parameter sniffing) and reuse it even when later values had very different data distributions.

💡 What does PSP bring to SQL Server 2022?

Parameter Sensitive Plan (PSP) optimization can maintain multiple plan variants for the same query, tuned for different parameter selectivities. A dispatcher chooses the appropriate variant for the current parameter values.

Query Store: Memory of Plans, Memory of Mistakes

2025-10-26 · 2 min

Query Store is SQL Server’s long-term memory: it records plans, decisions, and sometimes mistakes. By retaining query execution history, it allows DBAs to track how performance evolves and learn from regressions. Think of it as a diary of previous days, sometimes full of insights, sometimes regrets.

🧠 How Query Store works

Queries processed by SQL Server may be captured in Query Store, together with execution plans and runtime statistics. Over time, the engine accumulates evidence about which plans performed well and which caused regressions.

PAGE Restore: Database Surgery

2025-10-24 · 3 min

When a database contains billions of data pages, a full restore can feel like a heart transplant. Sometimes, however, a precise operation is enough: restoring only the damaged page. PAGE restore is SQL Server’s surgical procedure for repairing a fragment rather than restoring the entire database.

🧩 The idea

SQL Server stores data in 8 KB pages. When a page is damaged by an I/O problem, disk failure, or checksum error, the engine can mark it as suspect. Under the right conditions, you can restore only the affected page from backup, without restoring the entire database or data file.

Ghost Cleanup Task in Action

2025-10-23 · 3 min

SQL Server resembles an organism that can keep itself clean. When a row is deleted, its ghost does not disappear immediately — it remains in the data structure like a trace of a dead cell. Only the Ghost Cleanup Task arrives later to tidy things up quietly and restore balance.

It is SQL Server’s immune system: working in the background, out of sight, to keep the database from filling up with dead records.

SQL Server Memory Internals: What Happens in the Buffer Pool

2025-10-22 · 3 min

Behind every operation lies memory: Buffer Pool, Memory Clerks, Lazy Writer, and PLE (Page Life Expectancy). They are at the heart of SQL Server, and a sharp PLE drop can be a warning sign. Understanding how SQL Server manages data pages is essential for meaningful tuning.

“What does not fit in memory will come back from disk for revenge.”


🧠 SQL Server memory architecture

SQL Server has its own memory-management mechanisms, working alongside the operating system. This lets it respond to workload demands and manage internal allocations.

Ghost Records: Ghosts in the Database

2025-10-16 · 3 min

The database is haunted. Not in a horror movie, but in the DMV sys.dm_db_index_physical_stats. When you delete a row, SQL Server does not necessarily remove it immediately. Instead, it leaves behind a ghost record waiting for the ghost cleanup task to perform its exorcism.

This approach supports transactional rollback and avoids unnecessary disruption during DELETE. The engine prefers to mark a record as deleted rather than immediately rearrange the data page.

DELETE vs TRUNCATE: When Does SQL Server Really Clean Up?

2025-10-15 · 2 min

Both commands remove data. But one uses surgical precision, while the other brings a broom. DELETE and TRUNCATE can appear similar — both can leave a table empty. Under the hood, however, SQL Server performs very different operations.

DELETE — the surgeon with a magnifying glass

DELETE operates row by row. Each deleted row is logged in the transaction log, allowing the operation to be rolled back with ROLLBACK.

That provides precision: you can use WHERE, DELETE triggers fire, and foreign-key relationships are respected. But there is a price: log usage increases, and deleting many rows can be expensive.