Some SQL Server queries consume more than CPU and data-page I/O. During execution, they may also require temporary working memory for operations such as sorting, hashing, aggregation, index creation, and columnstore processing. This temporary allocation is commonly called a memory grant, query execution memory, or workspace memory.
Incorrect grants create two opposite problems. If the grant is too small, sort or hash operators may write intermediate data to disk, producing a spill. If the grant is too large, the query reserves more memory than it needs and can make other queries wait. The objective is therefore not to maximize the grant, but to make the grant appropriate for the query’s actual working set.
How SQL Server calculates a memory grant
When a query is compiled, the optimizer estimates how many rows will flow through each operator and how wide those rows will be. Those estimates influence the amount of memory requested by operators such as Sort, Hash Match, and Hash Aggregate.
At runtime, the query requests the calculated amount. SQL Server may grant all or only part of that amount, depending on available query execution memory and concurrent demand. The actual execution plan exposes useful information in the MemoryGrantInfo element, including values such as RequestedMemory, GrantedMemory, MaxUsedMemory, and, in supported versions, memory grant feedback status.
A large difference between requested and maximum used memory can indicate an oversized grant. A plan warning combined with insufficient working memory can indicate an undersized grant and a spill.
What a spill means
A sort or hash operator spills when it cannot keep all required intermediate data in its granted memory. SQL Server can continue by writing temporary work files, usually involving tempdb, but the extra physical I/O can significantly increase execution time and tempdb activity.
Actual execution plans may display Sort Warnings, Hash Warnings, or other spill-related information. Detailed spill events can also be captured with Extended Events in supported versions. A single spill does not automatically prove that a query is defective, but repeated spills on a high-volume or frequently executed workload deserve investigation.
Start with active memory grants
The sys.dm_exec_query_memory_grants DMV shows queries that have received or are waiting for query execution memory. The following query is a practical first diagnostic:
SELECT
mg.session_id,
mg.request_id,
mg.request_time,
mg.grant_time,
mg.requested_memory_kb,
mg.granted_memory_kb,
mg.required_memory_kb,
mg.used_memory_kb,
mg.max_used_memory_kb,
mg.wait_time_ms,
mg.queue_id,
st.text AS sql_text
FROM sys.dm_exec_query_memory_grants AS mg
OUTER APPLY sys.dm_exec_sql_text(mg.sql_handle) AS st
ORDER BY
mg.granted_memory_kb DESC,
mg.requested_memory_kb DESC;If grant_time is null, the request may still be waiting for memory. High wait_time_ms values combined with large requested grants are particularly important. A single large grant is not necessarily a problem; the larger risk is many large grants competing at the same time.
Monitoring historical behavior
The DMV describes current activity, not the complete history of the workload. For recurring problems, use Query Store, actual execution plans, Extended Events, and performance counters. Query Store can help identify repeating statements and compare plan behavior over time. The plan XML can then be inspected for MemoryGrantInfo and execution warnings.
At the instance level, the Memory Grants Pending and Memory Grants Outstanding counters are useful indicators. Persistent pending grants may point to excessive concurrency, large individual requests, or insufficient memory available for query execution. These counters should be interpreted together with wait statistics, query duration, CPU, and I/O.
Why grants become too large
Oversized grants commonly occur when the optimizer estimates that intermediate results will be much larger than they really are. Possible causes include stale statistics, inaccurate cardinality estimates, wide row projections, unnecessary columns, and queries that carry too many rows into a later sort or aggregate.
Start by removing columns the query does not need. Avoid SELECT * in production query paths, especially when large variable-length columns are involved. Reducing row width can lower the memory needed by downstream operators.
Apply selective filters as early as the logical design allows, and make sure join predicates are correct and supported by an appropriate indexing strategy. An index may reduce the number of rows that reach a sort or change the join strategy, but every index also has storage and write-maintenance costs.
How to reduce spills and incorrect grants
- Inspect the actual plan: Compare estimated and actual row counts at the operators that request memory. Large discrepancies often explain the grant problem.
- Review statistics: Check whether relevant statistics are maintained and whether they represent the current data distribution. Use your normal statistics maintenance policy and test changes before production deployment.
- Reduce the input set: Filter earlier, avoid unnecessary joins, and project only required columns.
- Review ordering: Remove an
ORDER BYthat the consumer does not require. An unnecessary sort in an intermediate query layer can be expensive. - Validate indexing: A suitable access path can reduce rows, avoid a sort, or improve a join. Measure both read and write effects.
Do not treat every spill as an indexing problem. The correct fix may be a statistics update, a query rewrite, a data-model change, or a plan-shape correction.
Memory Grant Feedback
SQL Server can adjust memory grants for repeated statements using information from previous executions. Batch mode Memory Grant Feedback was introduced in SQL Server 2017, row mode support followed in SQL Server 2019, and SQL Server 2022 added Query Store-based persistence and percentile-related improvements.
The feature does not repair the first execution retroactively. It uses execution history to refine grants for subsequent executions. This can reduce excessive grants and address repeated spills, but it is not a substitute for accurate statistics and sound query design.
Queries whose memory needs vary substantially by parameter values can be difficult for feedback mechanisms. SQL Server may detect unstable behavior and stop adjusting a statement. For that reason, investigate parameter sensitivity, data distribution, and plan quality rather than assuming that feedback will solve every workload.
Database-scoped configuration values can be inspected with:
SELECT
name,
value,
value_for_secondary
FROM sys.database_scoped_configurations
WHERE name LIKE '%MEMORY_GRANT_FEEDBACK%';For SQL Server 2022 persistence behavior, Query Store must be enabled and operating in READ_WRITE mode. Establish a baseline before changing compatibility levels or database-scoped settings so that improvements and regressions can be measured.
Hints and Resource Governor
The MIN_GRANT_PERCENT and MAX_GRANT_PERCENT query hints can constrain memory grant behavior for a specific statement. They should be used carefully. An overly restrictive value can increase spills, while an overly generous value can worsen concurrency. Any hint should be backed by repeatable testing, monitoring, and a rollback plan.
Resource Governor can help isolate workloads when different applications compete for query execution memory. It is a containment and workload-management tool, not a replacement for correcting a poorly estimated or unnecessarily wide query.
Practical checklist
- Inspect actual plans for sort, hash, and execution warnings.
- Use
sys.dm_exec_query_memory_grantsto find active and waiting requests. - Compare requested, granted, used, and maximum-used memory.
- Compare estimated and actual row counts.
- Review statistics, filters, joins, projections, and indexes together.
- Check Query Store and Memory Grant Feedback status.
- Do not increase server memory before addressing avoidable query and workload inefficiencies.
Conclusion
Memory grant problems are not always a simple “the server needs more RAM” issue. A small grant can cause spills and tempdb I/O, while a large grant can reduce concurrency and make unrelated queries wait. The most reliable approach combines actual execution plans, DMV data, statistics maintenance, Query Store history, and workload-level measurements.
When a query produces only the rows and columns it needs, statistics provide useful information, access paths are appropriate, and Memory Grant Feedback is monitored rather than blindly trusted, query memory usage becomes more predictable and easier to operate.
0 Comments