Instant Download Pro SQL Server 2022 Wait Statistics: A Practical Guide to Analyzing Performance in SQL Server and Azure SQL Database, 3rd Edition Thomas Larock PDF All Chapters
Instant Download Pro SQL Server 2022 Wait Statistics: A Practical Guide to Analyzing Performance in SQL Server and Azure SQL Database, 3rd Edition Thomas Larock PDF All Chapters
com
https://ebookmass.com/product/pro-sql-server-2022-wait-
statistics-a-practical-guide-to-analyzing-performance-in-
sql-server-and-azure-sql-database-3rd-edition-thomas-
larock-2/
OR CLICK BUTTON
DOWNLOAD NOW
https://ebookmass.com/product/pro-sql-server-2022-administration-a-
guide-for-the-modern-dba-3rd-edition-peter-a-carter/
ebookmass.com
https://ebookmass.com/product/microsoft-sql-server-2016-a-beginners-
guide-sixth-edition-petkovic/
ebookmass.com
https://ebookmass.com/product/sql-server-2022-administration-inside-
out-1st-edition-randolph-west/
ebookmass.com
https://ebookmass.com/product/microsoft-sql-server-2019-a-beginners-
guide-7th-edition-retail-edition-dusan-petkovic/
ebookmass.com
https://ebookmass.com/product/pro-t-sql-2022-2nd-edition-elizabeth-
noble/
ebookmass.com
Thomas LaRock and Enrico van de Laar
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Apress imprint is published by the registered company APress
Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
This book is dedicated to all the accidental database administrators,
developers, and anyone who has written a database query and wondered
“what the hell is taking so long?”
Also, for Roy, Moss, and anyone else who decided to turn it off and back on
again.
Introduction
“Write the book you wish someone else would have written and handed
to you when you were starting as a DBA.”
Those words were spoken to me by my friend and mentor, Kevin
Kline, roughly 13 years ago. At the time I was writing my first book,
DBA Survivor, and I asked Kevin for advice on how to approach the
project. His answer gave me clarity, and I’ve used the same approach for
this book you are now reading.
At the time I started as a junior DBA, Tom Davidson’s well-known
SQL Server 2005 Waits and Queues whitepaper was years away from
publication. What I knew about waits I would find using DBCC
statements against (the artist formally known as) Sybase ASE and SQL
Server 2000 instances.
In other words, I didn’t know much.
With the release of SQL Server 2005 and the publication of the
Davidson whitepaper, wait statistics became a viable tuning
methodology. Administrators and developers could now use waits and
queues to understand exactly why a query was running longer than
expected. Overnight our team transitioned from reacting to query
performance issues to being proactive in understanding which
resources the overall database workload needed most.
Every request sent to a database server has the same constraints:
memory, processing, disk, network, and locking/blocking. It doesn’t
matter if you want to rely solely on execution plans for query tuning;
the physical and logical constraints for the query remain the same: they
are just presented differently in an execution plan. The waits and
queue tuning methodology reduces the complexity and time
necessary for query performance tuning by an order of magnitude.
Once you understand how the database engine processes requests,
how waits happen, and how to track them, you are well on your way to
being an expert in query performance tuning.
And that’s the goal of this book. When you are done reading, I want
you to have all the skills necessary to be an expert in query
performance tuning. That’s the book I wish someone would have
written and handed to me when I was first starting as a DBA.
To reach the goal, this book has been split into two unequal parts.
Part I, “Foundations of Wait Statistics Analysis,” provides details on how
the database engine processes a query (officially called a request, which
is sent by a session, after a connection to the instance is established)
followed by information on how to query wait statistics information
through various SQL Server dynamic management views (DMVs). Part I
finishes with an overview of the Query Store feature and guidance on
how to create and gather metrics to build your own baselines.
Part II, “Wait Types,” dives into specific waits, the causes, some
examples, and possible resolutions. The chapters are divided by wait
categories, which is a bit tricky as some waits (such as PAGEIOLATCH)
have overlap between more than one possible constraint (memory and
disk). Therefore, the chapters break down specific waits into categories
by CPU, IO, backups, locks, latches, high-availability and disaster-
recovery, preemptive, background and miscellaneous, and In-Memory
OLTP.
Yes, waits for background and miscellaneous are included, despite
their being benign for query performance. It’s important for you to
know why (and when) these waits happen and when they are safe to
ignore (they usually are, but not always).
One thing to note, the examples in this book use a database named
GalacticWorks. This is a modified version of AdventureWorks I use for a
variety of demos when teaching my classes. The examples in the book
will work with AdventureWorks, so don’t panic about not having
GalacticWorks; you’ll be fine with most versions of AdventureWorks.
When you finish this book, I want you to have the confidence to
tackle any query performance tuning problem. You’ll have the details,
information, and knowledge necessary to be an expert. And maybe
soon enough, you’ll be teaching others and maybe someday write your
own book, too.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit http://www.apress.com/source-code.
Acknowledgments
There are many people to acknowledge and thank for helping me with
this book. I’ll do my best to include as many as I can, but please don’t be
offended if I forget you; it’s not on purpose.
I’ll start with my wife, Suzanne, for her patience as I spent many off-
hours completing this book. Oh, and for all the time I’ve spent away
from home for the past 15 years.
Thanks to Bob Ward of Microsoft for helping uncover new SQL 2022
features, as well as your willingness to share your knowledge on SQL
Server for the past 25 years. And thanks for your time in Barcelona in
2006 when you inspired me to want to learn more about SQL Server.
Thanks to my partner in #TeamData, Karen Lopez, for your help,
support, and friendship for many years. I became a better technical
writer and presenter by learning from you.
Thanks to Kevin Kline for your guidance and support as I left my
career as a production DBA to become a Technical Advocate and for
providing an example of what proper community leadership looks like.
To Buck Woody, for your support in helping me understand my
strengths and your guidance in career opportunities through the years.
To Craig and Vinny, for giving me the opportunity to fail as a DBA,
and to Frank and Lori for not letting it happen as much as it should
have.
To Rie, Betsy, Rochelle, and everyone on the Microsoft Community
team for awarding me the Microsoft MVP status all these years.
Finally, to Jonathan, for thinking of me when it came time to update
this book for SQL 2022. Thank you for the opportunity to write another
book for you, 12 years later.
Table of Contents
Part I: Foundations of Wait Statistics Analysis
Chapter 1:Wait Statistics Internals
A Brief History of Wait Statistics
The SQLOS
Schedulers, Tasks, and Worker Threads
Sessions
Requests
Tasks
Worker Threads
Schedulers
Putting It All Together
Wait Statistics
Summary
Chapter 2:Querying SQL Server Wait Statistics
sys.dm_os_wait_stats
sys.dm_os_waiting_tasks
Understanding sys.dm_os_waiting_tasks
Querying sys.dm_os_waiting_tasks
sys.dm_exec_requests
Understanding sys.dm_exec_requests
Querying sys.dm_exec_requests
sys.dm_exec_session_wait_stats
Combining DMVs to Detect Waits Happening Now
Viewing Wait Statistics Using Perfmon
Capturing Wait Statistics Using Extended Events
Capture Wait Statistics Information for a Specific Query
Analyzing Wait Statistics on a Per-Query Basis Using Execution
Plans
Summary
Chapter 3:The Query Store
What Is the Query Store?
Enabling the Query Store
Enable the Query Store Using SSMS
Enable the Query Store Using T-SQL
Query Store Architecture
How Wait Statistics Are Processed in the Query Store
Accessing Wait Statistics Through Query Store Reports
Accessing Wait Statistics Through Query Store DMVs
Summary
Chapter 4:Building a Solid Baseline
What Are Baselines?
Visualizing Your Baselines
Baseline Types and Statistics
Baseline Pitfalls
Too Much Information
Know Your Metrics
Find the Big Measurement Changes
Use Fixed Intervals
Building a Baseline for Wait Statistics Analysis
Reset Capture Method
Delta Capture Method
Using SQL Server Agent to Schedule Measurements
Wait Statistics Baseline Analysis
Summary
Part II: Wait Types
Chapter 5:CPU-Related Wait Types
CXPACKET
What Is the CXPACKET Wait Type?
Lowering CXPACKET Wait Time by Tuning the Parallelism
Configuration Options
Lowering CXPACKET Wait Time by Resolving Skewed
Workloads
Introduction of the CXCONSUMER Wait Type
CXPACKET Summary
SOS_SCHEDULER_YIELD
What Is the SOS_SCHEDULER_YIELD Wait Type?
Lowering SOS_SCHEDULER_YIELD Waits
SOS_SCHEDULER_YIELD Summary
THREADPOOL
What Is the THREADPOOL Wait Type?
THREADPOOL Example
Gaining Access to Our SQL Server During THREADPOOL
Waits
Lowering THREADPOOL Waits Caused by Parallelism
Lowering THREADPOOL Waits Caused by User Connections
THREADPOOL Summary
Chapter 6:IO-Related Wait Types
ASYNC_IO_COMPLETION
What Is the ASYNC_IO_COMPLETION Wait Type?
ASYNC_IO_COMPLETION Example
Lowering ASYNC_IO_COMPLETION Waits
ASYNC_IO_COMPLETION Summary
ASYNC_NETWORK_IO
What Is the ASYNC_NETWORK_IO Wait Type?
ASYNC_NETWORK_IO Example
Lowering ASYNC_NETWORK_IO Waits
ASYNC_NETWORK_IO Summary
CMEMTHREAD
What Is the CMEMTHREAD Wait Type?
Lowering CMEMTHREAD Waits
CMEMTHREAD Summary
IO_COMPLETION
What Is the IO_COMPLETION Wait Type?
IO_COMPLETION Example
Lowering IO_COMPLETION Waits
IO_COMPLETION Summary
LOGBUFFER and WRITELOG
What Are the LOGBUFFER and WRITELOG Wait Types?
LOGBUFFER and WRITELOG Example
Lowering LOGBUFFER and WRITELOG Waits
LOGBUFFER and WRITELOG Summary
RESOURCE_SEMAPHORE
What Is the RESOURCE_SEMAPHORE Wait Type?
RESOURCE_SEMAPHORE Example
Lowering RESOURCE_SEMAPHORE Waits
RESOURCE_SEMAPHORE Summary
RESOURCE_SEMAPHORE_QUERY_COMPILE
What Is the RESOURCE_SEMAPHORE_QUERY_COMPILE Wait
Type?
RESOURCE_SEMAPHORE_QUERY_COMPILE Example
Lowering RESOURCE_SEMAPHORE_QUERY_COMPILE Waits
RESOURCE_SEMAPHORE_QUERY_COMPILE Summary
SLEEP_BPOOL_FLUSH
What Is the SLEEP_BPOOL_FLUSH Wait Type?
SLEEP_BPOOL_FLUSH Example
Lowering SLEEP_BPOOL_FLUSH Waits
SLEEP_BPOOL_FLUSH Summary
WRITE_COMPLETION
What Is the WRITE_COMPLETION Wait Type?
WRITE_COMPLETION Example
Lowering WRITE_COMPLETION Waits
WRITE_COMPLETION Summary
Chapter 7:Backup-Related Wait Types
BACKUPBUFFER
What Is the BACKUPBUFFER Wait Type?
BACKUPBUFFER Example
Lowering BACKUPBUFFER Waits
BACKUPBUFFER Summary
BACKUPIO
What Is the BACKUPIO Wait Type?
BACKUPIO Example
Lowering BACKUPIO Waits
BACKUPIO Summary
BACKUPTHREAD
What Is the BACKUPTHREAD Wait Type?
BACKUPTHREAD Example
Lowering BACKUPTHREAD Waits
BACKUPTHREAD Summary
Chapter 8:Lock-Related Wait Types
Introduction to Locking and Blocking
Lock Modes and Compatibility
Locking Hierarchy
Isolation Levels
Querying Lock Information
LCK_M_S
What Is the LCK_M_S Wait Type?
LCK_M_S Example
Lowering LCK_M_S Waits
LCK_M_S Summary
LCK_M_U
What Is the LCK_M_U Wait Type?
LCK_M_U Example
Lowering LCK_M_U Waits
LCK_M_U Summary
LCK_M_X
What Is the LCK_M_X Wait Type?
Discovering Diverse Content Through
Random Scribd Documents
people according to their capacity, and the more gifted according to
their abilities. Certain fundamental truths are therefore set forth in the
Law and the Prophets in an authoritative, poetical, or dialectical
style; but the higher order of intellects are encouraged to search for
proper proofs. Thus the whole nation is addressed by Isaiah: ‘Lift up
your eyes on high and see who hath created these,’ and the like.
Also the chief of the Prophets tells the Israelites: ‘Hear, O Israel, the
Lord is our God; the Lord is One.’ Those who are more highly
endowed than their fellow-men are exhorted, either directly or
indirectly, to follow the course which is suitable to them. The direct
exhortation to philosophical research is contained in the words:
‘Know then this day, and take it to thy heart, that the Lord He is God,’
&c.; and indirectly it is contained in the commandment [16]to love and
to fear God, as has been explained by R. Moses Maimonides.—The
study of science will certainly be of use to the scholar; it leads to a
knowledge of the created things, and through these to a knowledge
of the Creator. Such study may even be considered as necessary to
the Jewish scholar, though not to the ordinary Jew. The scholar
must, however, not entirely rely on his research, but on that which is
taught in the Law. In this the scholar and the ordinary man are equal,
that both accept the teaching of the Torah as infallible; only with this
difference, that the scholar can in addition satisfy his thirst for
knowledge and confirm by scientific proof what he has already
accepted as true on the authority of the Bible.”
1. The first principle: The belief in the existence of the Creator; that
is, the belief that there exists a Being who requires no other cause
for His existence, but is Himself the cause of all beings.
2. The second principle: The belief in the Unity of God; that is, the
belief that the Being who is the cause of everything in existence is
One; not like the unity of a group or class, composed of a certain
[21]number of individuals, or the unity of one individual consisting of
various constituent elements, or the unity of one simple thing which
is divisible ad infinitum, but as a unity the like of which does not
exist.
3. The third principle: The belief in the Incorporeality of God; that is,
the belief that this One Creator has neither bodily form nor
substance, that He is not a force contained in a body, and that no
corporeal quality or action can be attributed to Him.
4. The fourth principle: The belief in the Eternity of God; that is, the
belief that God alone is without a beginning, whilst no other being is
without a beginning.
7. The seventh principle: The belief that our teacher Moses was the
greatest of all prophets, both those before him and those after him.
8. The eighth principle: The belief in the Divine origin of the Law; the
belief that the whole Pentateuch was communicated to Moses by
God, both the precepts and the historical accounts contained therein.
9. The ninth principle: The belief in the integrity of the Law; that both
the written and the oral Law are of Divine origin, and that nothing
may be added to it or taken from it. [22]
10. The tenth principle: The belief that God knows and notices the
deeds and thoughts of man.
11. The eleventh principle: The belief that God rewards those who
perform the commandments of His Law, and punishes those who
transgress them.
12. The twelfth principle: The belief that Messiah will come at some
future time, which it is impossible for us to determine; that he will be
of the house of David, and will be endowed with extraordinary
wisdom and power.
13. The thirteenth principle: The belief in the revival of the dead, or
the immortality of the soul.
These thirteen principles (שלשה עשר עקרים) may be divided into three
groups, according to their relation to the three principles:—1.
Existence of God. 2. Revelation. 3. Reward and punishment. The
first group includes the first five principles, the second the next four,
and the third the remaining four. In this order they will now be
considered.
[Contents]
“Lift up your eyes on high, and behold who hath created these? Who
is He who bringeth them forth by number? All of them He calleth by
name, by the greatness of His might, and for that He is strong in
power, not one is lacking” (Isa. xl. 26). “The heavens declare the
glory of God, and the firmament sheweth His handywork” (Ps. xix. 2).
The regularity in the rising and setting of the heavenly bodies, which
enables us to foretell the exact time and duration of an eclipse of the
sun or the moon, is certainly a strong argument for the belief that
there is a mighty and wise Creator who fixed the laws in accordance
with which these luminaries move.
“Beautiful are the luminaries which our God has created. He has
formed them with knowledge, reason, and understanding; He
endowed them with power and strength to rule in the midst of the
world. Full of splendour and beaming with light, they illumine the
whole world; they rejoice when they rise, they are glad when they
set, doing in reverence the will of their Master” (Sabbath Morning
Service).
A very general object of worship were the stars. Rabbi Jehudah ha-
Levi, in Kuzari iv. 1, in trying to explain the origin of this practice,
says as follows:—“The spheres of the sun and the moon do not
move in the same way. A separate cause or god was therefore
[26]assumed for each, and people did not think that there was a
higher force on which all these causes depended.” The ancient
monuments and the treasures stored up in our museums show how
great was the variety of forms which idolatry took, and to how great
an extent people adhered, and still adhere, to this kind of worship.
But there have been thinkers and philosophers even among the
idolatrous nations who sought a unity in the construction and working
of the universe, and early arrived at the idea of a First Cause as the
sole source of all that exists.
2. The fact that the influence of the Divine power makes itself
perceptible to the observing eye of man everywhere produced
another kind of human error: Pantheism (All-God). Modern
Pantheism dates from Spinoza; but long before Spinoza, when the
secret forces at work in the changes noticed by us in all material
objects were recognised as properties inherent in the substance of
things, these forces were considered as the sole independent
causes of the existing universe, and the combination of these forces,
called Nature, was considered to be the First Cause, or God. A
modification of this theory is contained in the philosophy of Spinoza.
According to this great philosopher’s system, the universe in its
entirety has the attributes of the Deity: there exists nothing but the
Substance (God), its attributes, and the various ways in which these
attributes become perceptible to man. Spinoza tried to defend
himself from the reproach of describing God as corporeal, but he did
not succeed. The attribute of extension or space which God
possesses, according to Spinoza, is only conceivable [27]in relation
to corporeal things. The philosophy of Spinoza is in this dilemma:
either God is corporeal, or the corporeal world does not exist. Both
assumptions are equally absurd. It is true, in one of his letters he
complains that he has been misrepresented, as if he believed God to
consist of a certain corporeal mass. But we cannot help assuming
the existence of a certain corporeal mass, and if this is not God, we
must distinguish in our mind God and something that is not God,
contrary to the fundamental doctrine of Pantheism. Besides, there
are many incongruities and improbabilities involved in this theory. It
has no foundation for a moral consciousness. The wicked and the
good are alike inseparable from God. They both result with necessity
from the attributes of God, and they cannot be otherwise than they
actually are. If we, by the consideration that injury done to us by our
fellow-man was not done by that person alone, but by a series of
predetermined necessary causes, may be induced to conquer hatred
against the apparent cause of our injury, we may equally be induced
by the same reasoning to consider the kindness and benefits of our
friends not worthy of gratitude, believing that they were compelled to
act in this manner, and could not act otherwise.
In the Bible atheism is stigmatised as the source of all evils. Thus the
patriarch Abraham suspected the [28]people of Gerar, that there was
“no fear of God” in the place, and was afraid “they might slay him”
(Gen. xx. 11); whilst Joseph persuaded his brothers to have
confidence in him by the assertion, “I fear God” (Ib. xlii. 18). The first
instance of an atheist we meet in Pharaoh, king of Egypt, when he
defiantly said, “I know not the Lord, neither will I let Israel go” (Exod.
v. 2). Another form of atheism is warned against in the words of
Moses: “Lest thou sayest in thine heart, My strength and the power
of my hand has got for me all this wealth” (Deut. viii. 17); and “Lest
they say, Our hand is high, and it is not the Lord that hath done all
this” (Ib. xxxii. 27). The prophets likewise rebuke the people for want
of belief in God. In the Psalms, the crimes and evil designs of
oppressors are traced to godlessness. “The wicked says in his heart,
There is no God” (Ps. xiv. 1). But this atheism of the Bible is not a
theoretical or dogmatic one; it is not the result of thought, or of deep
inquiry into the causes of things, but merely the voice of an evil
inclination which tempts man to act contrary to the command of God,
and assures him of immunity, under the impression that his actions
are not watched by a higher authority. In post-Biblical literature we
meet with the phrase, לית ִּד ין ולית ַּד ָּין“There is no judgment, and there
is no judge,” as the basis of atheism.
All these various systems of religion have this in common, that they
attempt to remove from religion everything that cannot be
comprehended by human reason. But all attempts to substitute
human reason for Divine authority have failed. A limit has been set to
human reason, and that cannot be overcome. In every system of
religion—the natural and the rational included—there is a mystic
element, which may be enveloped in a mist of phrases, but remains
unexplained. Whether we call the Creator and Ruler of the universe
God, Deus, or Theos, His relation to the universe, and to man in
particular, cannot be [30]determined by the laws which determine the
natural phenomena in the universe, created by His Will.
The first principle declared in our creed is this: God is not only the
Creator of the heavens and the earth, with all their hosts; He is also
the constant ruler of all created beings; He is בורא ומנהיג. We
therefore praise Him in our daily Morning prayer as “Doing wonders;
renewing in His goodness the work of the creation every day.” When
we observe the ordinary phenomena in nature, occurring in
accordance with certain fixed laws which have been discovered and
described by man, we see in them the greatness of the Creator by
whose will these laws are still in force, and by whose will any or all of
these laws may one day cease to continue.
It has been asserted that any interruption or change [32]of these fixed
laws would indicate a weakness and want of foresight on the part of
the Creator, and a fault in the plan of the Creation. This notion has
led people either to deny the truth of the Biblical accounts
concerning the miracles wrought by the Almighty, or to admit the
correctness of the facts while denying their miraculous character, or
to consider the fixed laws of nature, together with their exceptions,
as designed in the original plan of the Creation. How short-sighted is
man! He cannot even fully comprehend his own short-sightedness!
God made him ruler over the works of His hands, and he presumes
to be the ruler of God Himself! When we learn from numerous
observations and experiments the law that seems to regulate certain
recurring phenomena, have we then fathomed the infinite wisdom of
God in the Creation? Do we know the reason which led Him to
produce certain things according to certain laws, and not otherwise?
Have we in discovering a law of nature obtained the power of
prescribing the same law to God, and disallowing Him to deviate
therefrom? Far be it from us human beings, dust and ashes, to
arrogate to ourselves such a right! It may even be one of the objects
with which miracles were wrought to teach us that we do not yet
know all things, that events may happen which we are unable to
foresee, that phenomena may appear which we are unable to
explain according to the laws hitherto discovered; in short, that our
knowledge and wisdom are limited.
The fact that God has created the universe ex nihilo has been
expressed by Jewish philosophers as follows:—God is the only
Being who demands no cause for His existence; the very idea of
God implies existence, [33]and cannot be conceived without it. All
other beings owe their existence to certain causes, in the absence of
which they would not exist. God alone is therefore only active,
without ever being passive, only cause without ever being effect,
whilst every other being is both active and passive, cause and effect;
it has been produced by certain causes, and is in its turn the cause
of the existence of other beings. In the first article a phrase
expressing this idea has been added: “And He alone is the active
cause of all things, whether past, present, or future.” By the addition
of this sentence it was intended to deny the Eternity of matter (קדמות
העולם). The reference to past, present, and future is to emphasise
the constant action of the Creator, and the dependence of the natural
forces on His Will. The first principle has, therefore, the following
form:—
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookmass.com