Over the next few days, I’m going to look at the wait stats that show up during different types of spills of different sizes. For no reason whatsoever, I’m going to start with sort spills. I’ll also cover hash and exchange spills, in case you were wondering just how long you’d have to sit here reading about them.
The point is not that spills are the sole things that cause these waits, it’s just to give you some things to potentially watch out for if you see these waits piling up and can’t pin down where they’re coming from.
In all the queries, I’m going to be using the MAX_GRANT_PERCENT hint to set the memory grant ridiculously low to make the waits I care about stick out.
For each query we run, we’re gonna execute the query, and then this query to look at session level wait stats.
SELECT desws.* FROM sys.dm_exec_session_wait_stats AS desws WHERE desws.session_id = @@SPID ORDER BY desws.wait_time_ms DESC;
No Strings Attached
Strings are horrible. The bigger they are, they worse they are. Nearly every time I see oversized string columns, I see them causing problems.
File that under obvious foreshadowing while we look at a sort that doesn’t involve any strings.
SELECT c.Id, c.CreationDate, c.PostId, c.Score, c.UserId FROM ( SELECT c.Id, c.CreationDate, c.PostId, c.Score, c.UserId, n = ROW_NUMBER() OVER ( ORDER BY c.PostId DESC ) FROM dbo.Comments AS c ) AS c WHERE c.n = 0 OPTION(MAX_GRANT_PERCENT = 0.0);
This query executes at DOP 8 in row mode, and the primary wait that racks up is IO_COMPLETION.
Remember when I told you to file that thing up there under another thing? Here’s why.
In this query, we’re also going to select the Text column from the Comments table , which is an nvarchar(700).
SELECT c.Id, c.CreationDate, c.PostId, c.Score, c.Text, --New c.UserId FROM ( SELECT c.Id, c.CreationDate, c.PostId, c.Score, c.Text, --New c.UserId, n = ROW_NUMBER() OVER ( ORDER BY c.PostId DESC ) FROM dbo.Comments AS c ) AS c WHERE c.n = 0 OPTION(MAX_GRANT_PERCENT = 0.0);
In this case, things get way worse. If you’re surprised, you should try reading blog posts; particularly this one.
Rather than ~16 seconds of spilling, we end up with a bit over four minutes of spilling. This is as the Mayans foretold, but the 2012 calendar was drunk and got the last two digits backwards.
Again, there are many potential causes of this wait, but on servers where I see them really piling up and ending up in top waits, there tends to be a dearth of memory and a lot of queries spilling to disk during sorts.
If you see this wait piling up, you may want to check out the query here to look for select queries that cause writes, which can indicate spills (among other things).
Thanks for reading!
If this is the kind of SQL Server stuff you love learning about, you’ll love my training. I’m offering a 75% discount on to my blog readers if you click from here. I’m also available for consulting if you just don’t have time for that and need to solve performance problems quickly.