Rowstore Adaptive Joins

In this day and age, join operations in SQL Server can be made using one of the following algorithm types: Nested Loops, Merge or Hash. In theory, each one provides better performance under different conditions (e.g. amount of data).

  • Nested Loops: One of the tables is designated as the outer and other as the inner table. Each row of the outer table, is validated against all rows from the inner table and if a match is found, the row is included in the result. Nested Loop is tipically preferred when tables are small. There are three variants for a Nested Loop Join:
    • Naive: Scans an entire table or index;
    • Index: Uses an existing index to seek data;
    • Temporary: Index is built as part of the query plan (and destroyed upon completion of the query);
  • Hash Match: Hash Match consumes two inputs, corresponding to the joined tables. A hash table is created using the first input (also known as Build), then the same is done for the second input (Probe). The process of creating a hash table starts with hashing joined key values of the Build table and placing them on the appropriate bucket, depending on the hash value. Afterwards, Probe is processed, same hash values are applied, target bucket is determined and finally the value is compared to the ones already inside. If there is a match and after SQL Server verifies that no hash collision happened, the row is returned. Build should always be smaller because it will be stored in memory.

And that’s it. No, I did not forget about Merge Join, it happens that Merge was just ignored (like Internet Explorer or Terms of Agreement). Adaptive Join allows SQL Server to choose between Nested Loops and Hash joins on the same execution plan, deferring this choice, so it can understand which one will be better, based on the query input.

So, if until now (at least in rowstore) there wasn’t a way to adapt to different workloads inside the same execution plan and specific join algorithms thrive under different conditions, how can, in theory, Adaptive Joins save the day?

The Horrors of Parameter Sniffing

Parameter sniffing is easily one of the most common problems that almost anyone who works with databases have to deal with. Well, to be fair, parameter sniffing is not a problem by itself. The problem is giving the power of choice to users. Choice is the root of all evil.

A store procedure gets executed for the first time, the plan is created based on its input and then is cached. If no recompile is done, the plan will remain the same and future executions will reuse it, regardless of the input. In theory that’s good, because bad things happen when there isn’t enough memory available – and creating new plans from scratch is quite expensive. The problem begins when, in a subsequent execution, the user changes the input in a way that the query returns a million rows, instead of ten. As mentioned in the previous section, each join type thrives under distinct conditions. If in the first execution, a small amount of data was scanned, SQL Server has potentially used Nested Loops and done something like an Index Seek plus a couple Key Lookups. In the later execution, when SQL Server tries to process a million rows using the same approach, it suddenly has a heart attack. Telephones start to ring and clients start o yell as its soul quickly ascends to heaven.

We can try defibrillating by using RECOMPILE, but if that query runs too often, CPU will quickly escalate to 100% and we lose the patient, again. We can also try to optimize the query to a particular case by specifying a join hint or using OPTIMIZE FOR hint, but even if we get a plan that fits appropriately to the majority of executions, the deviations will potentially cause SQL Server to die in agony. Dividing the store procedure into multiple store procedures according to the input, can do the trick, but in some cases, queries can be too complex, not to mention that business logic and magic numbers hardcoded in queries are generally not a good idea. So, what’s left besides a bunch of bad ideas?

Perhaps Adaptive Joins is the hero we deserve. Basically, SQL Server defines a threshold (related to the number of rows) that represents the tipping point from which becomes more efficient to use Nested Loops instead of Hash Match. Adaptive Join will start the execution as a Hash Join, then, after processing the input from the Build phase, it will compare the resulting number of rows to this threshold. If the number of rows is greater or equal, it will proceed execution, otherwise the algorithm type is change to Nested Loops.

Therefore, SQL Server becomes able to adapt a single plan to different workloads. If a large number of rows are being processed, it can use Hash Join, otherwise, if few rows are involved, Nested Loop Join will be chosen. No recompile. No hints. No Columnstore wizardry needed.

Now, let’s check if Adaptive Joins will live to the expectations.

Improvise Adapt Overcome

For the purposes of this demo, I’m using a sample of FootballData public stats. Additionally, I’ve added some data in order to facilitate the demonstration of some concepts and behaviors. Bear in mind that in Standard Edition you won’t be able to use this feature.

We’ll firstly set database compatibility level to 140 and execute a store procedure with two different parameters, so we can understand the behavior prior to SQL Server 2019.

CREATE OR ALTER PROCEDURE GetHomeVictoriesByTeamId      
	@TeamId INT      
	m.FTHG HomeGoals,  
	m.FTAG AwayGoals,    
	d.Att Attendance,  
	Matches m          
	MatchesDetails d ON = d.MatchDetails       
	m.HomeTeam = @TeamId AND 
	FTR = 'H' AND 
	d.Att > 20000           
ORDER BY       
	d.att DESC        
EXEC GetHomeVictoriesByTeamId 2
EXEC GetHomeVictoriesByTeamId 1

Ouch! Both execution plans used Nested Loops and Index Seek to retrieve results. The plan was created and cached in the first execution that retrieved 18 rows. Then SQL Server reused the plan to process 500304 victories from Benfica (Id = 1) and things got nasty. We can confirm in Messages that the second plan was not efficient.

By executing the same statement again with recompile, we can notice how a more appropriate plan differs. MatchesDetails’ Scan count dropped from 500304 to 5 and logical reads from 1597472 to 1539. That’s more like it! But, as we discussed, using option recompile is far from being always appropriate, due to the fact that it is a heavy resource consumer.

EXEC GetHomeVictoriesByTeamId 1 WITH RECOMPILE;

Next, we’ll set database compatibility level up to 150 and run the store procedure again, so we can see Adaptive Joins in action.

EXEC GetHomeVictoriesByTeamId 1;
EXEC GetHomeVictoriesByTeamId 2;
EXEC GetHomeVictoriesByTeamId 1;

By looking into the first execution plan, we’ll notice the “new” Adaptive Join operator (this looks intuitive), so it looks like we’re ready to adapt and overcome. There are a few things going on in this plan, so let’s analyze it step by step.

The properties of this operator will show us some interesting information, e.g. that the threshold for the algorithm to change to Nested Loops is 9607.83. We also can see that 500304 rows were returned, so the chosen join type was “HashMatch”. This is the expected behavior as the number of rows is higher than the threshold, hence not changing to Nested Loops.

If we recall the execution plan, it’s easy to corroborate this information. Since the number of rows exceeded the threshold and a Hash join was done, the execution went to the Index Scan branch. This can also be confirmed by the displayed number of rows that flowed through this operator, in this case 500304. Correspondingly, the lower Index Seek branch, had no rows.

The second plan, corresponding to an input that retrieves far less rows, shows a different execution branch. In the Adaptive Join operator info, it’s possible to notice that the chosen join algorithm type (NestedLoops) is appropriate to the number of rows – 18. It’s also visible that these rows were retrieved by an Index Seek instead of an Index Scan. So far, so good.

The third and last plan, with the same input as the first will be exactly the same, right? Well… Sadly no. Although the operators are the same and the execution went through the same branch, it looks like we landed on spillage village. Both Sort and Adaptive Join have warning signs on them, stating that data was spilled to tempdb and we can see that the query took longer to run. Despite that, IO statistics maintain the same values of the first execution.  Interestingly, this behavior is caused by another adaptive query processing feature that was explored in a previous post– Adaptive Memory Grant Feedback.

If you are lucky enough, after a couple executions, SQL Server will be able to adapt the memory grant to its ideal value and just like clouds, when these warnings disappear, it will be a beautiful day. Unfortunately, sometimes SQL Server isn’t able to do that and gives up on adapting the grant (for more details, check the mentioned post). Let’s execute the store procedure a couple more times and check the outcome.

EXEC GetHomeVictoriesByTeamId 1
GO 30

Under these circumstances, SQL Server wasn’t able to adapt the memory grant and we didn’t get the stable ending we were looking for. Nevertheless, things could be worse: The initial memory grant is fairly adequate, so no spills this time. Furthermore, the chosen join algorithm is appropriate, IO statistics and execution time are pretty similar too.

In conclusion, looks like Adaptive Joins can really improve the performance of our servers, with virtually no effort needed. Nonetheless, it’s probably not a good idea to go all-in and change your production server compatibility level to 150, hoping that the robots will do what they were programmed to do. You must have seen enough movies to know that it’s not how it ends. But seriously, Adaptive Joins won’t fix all problems related to parameter sniffing and can actually cause problems that aren’t easy to troubleshoot. So, it’s reasonable to proceed cautiously and make use of tools like Query Store to fix regressions.

Row Mode Adaptive Memory Grant Feedback

Memory Grants

Throughout the phases of query processing there are several memory consumers that the memory broker and the memory manager inside SQL Server try to handle efficiently.  From those, compile, cache and memory grant are amongst the most significant. 

Compile requires memory to build and search a proper plan out of all candidates, whereas cache represents the memory consumed to store compiled plans in cache for reuse. Lastly and most importantly, the memory grant represents a segment of server memory used to store temporary data while sorting and joining rows. The grant is reserved prior to the query execution and lasts for the query lifetime, its purpose is to improve query reliability under server load. The rationale is, a query with reserved memory is not only less likely to run out of memory while executing, but also to take the entire server memory.

Grants and Estimates

When SQL Server creates a compiled plan it calculates two parameters that will define the amount of requested memory:

  • Required memory: The memory required to create internal data structures that will handle sorts and hash joins. It is mandatory that this amount is available in order to the query to be executed. The wait type that is accumulated if memory isn’t available is RESOURCE_SEMAPHORE.
  • Additional memory: It’s used to store temporary rows in memory. This value depends intrinsically on the cardinality estimate of expected number of rows and their average size. It’s not required that this amount of memory is available, the data can be stored into disk instead, although depending on the quantity of data this can be as good as shooting yourself in the foot.

After deciding whether a memory grant is necessary or not, calculating the DOP and the memory limit for one query, these parameters are used to calculate the ideal query memory, i.e. the amount of memory the query needs to run properly, based on its cardinality estimate. Finally, SQL Server verifies if the ideal memory exceeds the per-query limit (reducing it if needed) and asks Resource Semaphore to grant the requested memory. 

Now, if memory grants are deeply related to cardinality estimate, what happens if the numbers we get are not accurate, for example due to outdated statistics? The answer is… Pain. But as some pains are worse than others, we also might be more or less miserable depending on whether SQL Server overestimates or underestimates the work it thinks it has to do. 

When SQL Server overestimates the work to be done in a particular query it will grant more memory than necessary. Although one might think that like money, there is no such thing as too much memory, that will come at a cost. This means we’re stealing memory from a limited source that feeds cache, buffer pool and other queries. In extreme cases this might cause queries to lack required memory, hence not executing. And to make things worse, until now, in row mode, this behavior would just keep repeating itself, execution after execution, until, potentially, the server dies in agony. 

On the other hand, if SQL Server underestimates the workload, it may not grant enough memory to keep things out of tempdb. If it was expecting a few rows and ended up having to deal with millions, it will spill data to disk in order to handle the mess and this may have a significant impact on performance. As in overestimates, SQL Server would not learn from its mistakes and data would just continuously be spilled to disk in each execution.

But… Could inadequate memory grants be the root of all evil? Probably not, but if wait types like IO_COMPLETION or RESOURCE_SEMAPHORE start to accumulate that might just be the case.

Doctor, My Memory Hurts

In such circumstances there are tools that can be used to diagnose and troubleshoot these issues. As SQL Server editions went by, the number of available tools also risen.  

In SQL Server 2012 Extended Events were added in order to help the diagnosis of these cases: sort_warning, hash_spill_details to improve tempdb spill diagnostics and query_memory_grant_usage to improve memory grant diagnostics. Also, two query memory grant options were made available (MIN_GRANT_PERCENT and MAX_GRANT_PERCENT) that allow to specify the minimum and maximum grant percentage (based on the memory grant that’s specified in the resource governor configuration) on a per query basis.

Later, SQL Server 2016 introduces the almighty Query Store and improves a couple of DMVs and Extended Events.

Lastly, in SQL Server 2017, the feature that is most closely related to the one we’re about to see was released: Batch Mode Adaptive Memory Grant Feedback. In fact, it is, basically, the same feature applied to a different context.  If you want to know more about Adaptive Memory Grant Feedback in Batch Mode check Niko’s explanation here

So, finally we’re in 2019 when SQL brought this feature to Row Mode. Let’s take a walk!

Row Mode Adaptive Memory Grant Feedback

For the purposes of this demo, I’m using a sample of FootballData public stats that I stored in a very simple and small database (no Contoso or AdventureWorks for you today). Also, keep in mind that this is an Enterprise Edition feature.

We’ll start with a lower compatibility level to confirm the behaviour prior to this feature.


Next, we’ll create a store procedure to intentionally create an evil memory grant.

@Team nvarchar(128)    
 DECLARE @TeamID int = (SELECT Id FROM Teams WHERE Name = @Team)    
    l.Country,l.Name, m.Date,   
    h.Name AS HomeTeam, a.Name as AwayTeam,   
    d.Att, d.Ref, d.HS, d.[AS], d.HST, d.AST,   
    d.HHW, d.AHW, d.HC, d.AC, d.HF, d.AF,  
    d.HFKC, d.AFKC, d.HO, d.AO, d.HY,  
    d.AY, d.HR, d.AR, d.Preview    
    Matches m (NOLOCK)    
    MatchesDetails d (NOLOCK) ON = d.MatchDetails    
    Teams h (NOLOCK)  ON m.HomeTeam =     
    Teams a (NOLOCK)   ON m.AwayTeam = a.Id    
    Stadiums s (NOLOCK)   ON s.Team = h.Id    
  Leagues l (NOLOCK)   ON m.League = l.Id    
    m.hometeam = @TeamID AND m.FTR = 'H'    
    l.Name, m.Date, m.FTHG, m.FTAG,    
    m.HTHG, m.HTAG, m.HTR, m.FTR, d.Preview    

And execute it as follows.

USE FStats
EXEC GetHomeVictoriesByTeam 'Benfica'

When we open the query execution plan, it’s visible a warning indicating an underestimate that resulted on a spill to disk. In order to view the MemoryGrantInfo, right-click on the SELECT, then choose properties.

If we keep executing this statement, we’ll watch SQL Server suffering from anterograde amnesia, just like Dory. The value of DesiredMemory will not change and the query will spill to disk, execution after execution. Now, let’s set the compatibility level to 150 and see if things change.

EXEC GetHomeVictoriesByTeam 'Benfica'

At first glance everything looks similar, we get that same warning in the query execution plan, but in the MemoryGrantInfo a new field named IsMemoryGrantFeedbackAdjusted is now visible with the value “NoFirstExecution”. That looks promising…

And in fact, when we execute it again, black magic starts to happen. This time SQL Server remembers that the desired memory wasn’t enough to sort the huge amount of Benfica’s home victories (incomprehensible mistake though) and requests more memory. This avoids spilling out to tempdb, as we can verify by the absence of the previous warning. Nevertheless, SQL Server hasn’t yet found the ideal memory grant size and is still trying to get it, as we can see by the value of IsMemoryGrantFeedbackAdjusted – “YesAdjusting“.

After a couple executions, SQL Server is finally able to achieve the ideal memory grant as we can confirm by the value of IsMemoryGrantFeedbackAdjusted – “YesStable“. Awesome! From now on, executing this query is all about stability and happiness. Or is it?!

The premise here is that SQL Server will try to use the result from a previous execution in order to adjust the memory grant in the following. In the previous example that was rather simple, because we’ve used the same parameter across executions. Contrarily, the real world, full of evil users, tends to be more dynamic. So, what will happen if we change parameters between executions? In order to determine that we’ll intercalate the parameters of two executions and create an Extended Event to catch those spills. As Katy Perry said, “don’t be afraid to catch spills, ride Extended Events and chase thrills”.

ADD EVENT sqlserver.sort_warning(
ADD TARGET package0.ring_buffer
--GOTO: Management > Extended Events > Sessions > DontBeAfraidToCatchSpills > Start Session
--GOTO: Management > Extended Events > Sessions > DontBeAfraidToCatchSpills > Watch Live Data

EXEC GetHomeVictoriesByTeam 'Benfica' 
EXEC GetHomeVictoriesByTeam 'Villareal'
GO 16

We’ve created an Extend Event using sqlserver.sort_warning because we know that, in this case, only the sort operation will spill to disk. Also note that we’re executing this block 16 times, so 32 executions of the store procedure are being done. The MemoryGrantInfo in the last execution plan will show us that SQL Server is still trying to adjust the memory grant.

Accordingly, the results of the Extended Event show queries spilling all over the place, as we can state by the various threads being displayed. When there isn’t enough memory on SQL Server to execute a sort operation within a query, the sort table will be written to disk and divided into multiple “passes”. Each pass represents an overhead and will increase the required time to complete the operation. The sort_warning_type indicates whether it was executed in single pass or consumed multiple passes. The results show that, in these circumstances, the sort operation was finished within one pass i.e. it was divided into 2 steps.

After 32 executions SQL Server hasn’t yet figured out the ideal memory grant. Perhaps if we try again it’ll succeed. Furthermore, what could possibly go wrong?

EXEC GetHomeVictoriesByTeam 'Benfica' 

Well… Actually, things got worse. Turns out that SQL Server will try to adjust the DesiredMemory until the 32nd execution, after that it just gives up on us. Note that the value of IsMemoryGrantFeedbackAdjusted changed to NoFeedbackDisabled. This means that, from now on, SQL Server will use the memory grant of the first execution, which in our case is far from good.

In conclusion, row mode adaptive memory grant is quite awesome, particularly in scenarios where is expectable that the query inputs have no or few variations. Otherwise, things can get unpleasant, as we saw, so it’s wise to be cautious.