Sql-server – How SQL determine page exists in Buffer pool (internal)

database-internalssql server

When we execute SQL query, then Relational Engine optimize it and pass query plan to Storage Engine which then ask for a page with actual data.

If data page isn't in memory, then SQL pull those pages from disk and place it in RAM.

How, in future, SQL determine if page, which Storage Engine asks, is already in memory? And which algorithm it uses to keep some free space for new pages?

Best Answer

How, in future, SQL determine if page, which Storage Engine asks, is already in memory?

To balance CPU and I/O throughput to achieve good performance and maximize hardware utilization, SQL Server includes 2 asynchronous I/O mechanisms - sequential read ahead and random prefetching

When SQL Server has to scan a large table, the storage engine will initiate the read ahead mechanism to ensure that pages are in memory and they are ready to scan before they are needed by the Query Optimizer.

If you are using Enterprise edition, then there is a mechanism called advanced scanning or merry-go-round scanning that will allow multiple tasks to share full table scans. This advance scanning avoids users to compete for buffer space and taxing other resources on the server.

And which algorithm it uses to keep some free space for new pages?

SQL Server (and Sybase as well :-) ) uses LRU (Least Recently Used) algorithm to keep track of pages that are aged in the buffer pool. It increments a counter every time a page is referenced and decrements the counter every time the lazy writer process sweeps the page.

Any worker thread will check the memory status of Buffer Pool to make sure that there are healthy number of Free pages to honor incoming new requests.

Note that : SQL Server will always keep a minimum number of free pages on the free list, so that it can serve incoming requests without any significant delay. The amount of free space is calculated based on Buffer Pool and amount of incoming requests.

IF there are no free buffers or very little left then :

You can use DMV (in 2005 and up) - sys.dm_os_buffer_descriptors to find the pages in the buffer pool.

Also, there are Memory Manager surface area changes in SQL Server 2012.

KB 2663912 :

Starting with SQL Server 2012, Multi-Page allocations and CLR allocations are also included in memory limits that are controlled by max server memory (MB) and min server memory (MB). This change provides a more accurate sizing ability for all memory requirements that go through the SQL Server memory manager. Carefully review your current max server memory (MB) and min server memory (MB) values after you upgrade to SQL Server 2012.

Highly recommend to read :