SlideShare a Scribd company logo
1 of 42
Download to read offline
© Brent Ozar Unlimited®. All rights reserved. 1
Download the slides: BrentOzar.com/go/engine
How to Think Like
the SQL Server Engine
BrentOzar.com/go/engine
Download the slides: BrentOzar.com/go/engine
We’re using Stack Overflow data.
Open source, licensed with Creative Commons
SQL Server: BrentOzar.com/go/querystack
XML dump: archive.org/details/stackexchange
I’m using SQL Server 2019,
compatibility level 150/2019.
My cost threshold for parallelism is 5.
© Brent Ozar Unlimited®. All rights reserved. 2
Download the slides: BrentOzar.com/go/engine
Download the slides: BrentOzar.com/go/engine
© Brent Ozar Unlimited®. All rights reserved. 3
Download the slides: BrentOzar.com/go/engine
Download the slides: BrentOzar.com/go/engine
Page Header
Index OR
Data Rows
Slot Array
8KB
© Brent Ozar Unlimited®. All rights reserved. 4
Download the slides: BrentOzar.com/go/engine
You: SQL Server.
Me: end user.
Download the slides: BrentOzar.com/go/engine
First query:
SELECT Id
FROM dbo.Users
© Brent Ozar Unlimited®. All rights reserved. 5
Download the slides: BrentOzar.com/go/engine
Your execution plan:
1. Shuffle through all of the pages,
saying the Id of each record out loud.
Download the slides: BrentOzar.com/go/engine
SQL Server’s execution plan
© Brent Ozar Unlimited®. All rights reserved. 6
Download the slides: BrentOzar.com/go/engine
SET STATISTICS IO ON
Logical reads: the number of 8K pages we read.
(7,405 x 8KB = 59MB)
Download the slides: BrentOzar.com/go/engine
That’s 15 reams.
© Brent Ozar Unlimited®. All rights reserved. 7
Download the slides: BrentOzar.com/go/engine
Let’s add a filter.
SELECT Id
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
Download the slides: BrentOzar.com/go/engine
Your execution plan:
1. Shuffle through all of the pages,
saying the Id of each record out loud,
if their LastAccessDate > ‘2014/07/01’.
© Brent Ozar Unlimited®. All rights reserved. 8
Download the slides: BrentOzar.com/go/engine
SQL Server’s execution plan
Download the slides: BrentOzar.com/go/engine
© Brent Ozar Unlimited®. All rights reserved. 9
Download the slides: BrentOzar.com/go/engine
Lesson:
Using WHERE
without a matching index
means scanning all the data.
(Andtherearesomeextrareadswhenqueriesgoparallel
–butmoreonthatinourmoreadvancedclasses.)
Download the slides: BrentOzar.com/go/engine
© Brent Ozar Unlimited®. All rights reserved. 10
Download the slides: BrentOzar.com/go/engine
Download the slides: BrentOzar.com/go/engine
Lesson:
Estimated Subtree Cost is a
rough measure of CPU and IO
work required for a query.
© Brent Ozar Unlimited®. All rights reserved. 11
Download the slides: BrentOzar.com/go/engine
Let’s add a sort.
SELECT Id
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate
Download the slides: BrentOzar.com/go/engine
Your execution plan
1. Shuffle through all of the pages,
writing down fields __________ for each record,
if their LastAccessDate > ‘2014/07/01’.
2. Sort the matching records by LastAccessDate.
© Brent Ozar Unlimited®. All rights reserved. 12
Download the slides: BrentOzar.com/go/engine
SQL Server’s execution plan
Download the slides: BrentOzar.com/go/engine
© Brent Ozar Unlimited®. All rights reserved. 13
Download the slides: BrentOzar.com/go/engine
Order By:
Cost is up about 2x
We needed space to
write down our results,
so we got a memory grant
Download the slides: BrentOzar.com/go/engine
You can see more in Properties
© Brent Ozar Unlimited®. All rights reserved. 14
Download the slides: BrentOzar.com/go/engine
You can’t always get what you want.
Memory is set when the
query starts, and not revised.
SQL Server has to assume
other people will run queries
at the same time as you.
Your memory grant can
change with each time that
you run a query.
* - This screenshot is froma different query toshowvariances.
Download the slides: BrentOzar.com/go/engine
And if you run out of memory…
© Brent Ozar Unlimited®. All rights reserved. 15
Download the slides: BrentOzar.com/go/engine
Let’s get all the fields.
SELECT *
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate
Download the slides: BrentOzar.com/go/engine
Your execution plan
1. Shuffle through all of the pages,
writing down fields __________ for each record,
if their LastAccessDate > ‘2014/07/01’.
2. Sort the matching records by LastAccessDate.
© Brent Ozar Unlimited®. All rights reserved. 16
Download the slides: BrentOzar.com/go/engine
That query sucks.
Download the slides: BrentOzar.com/go/engine
But why does it suck?
Do we work harder to read the data?
Do we work harder to write the data?
Do we work harder to sort the data?
Do we work harder to output the data?
© Brent Ozar Unlimited®. All rights reserved. 17
Download the slides: BrentOzar.com/go/engine
The sort cost
is now 97%...
Download the slides: BrentOzar.com/go/engine
Of a MUCH larger
overall cost.
© Brent Ozar Unlimited®. All rights reserved. 18
Download the slides: BrentOzar.com/go/engine
SELECT ID SELECT *
No order 6 6
ORDER BY 13 871
Download the slides: BrentOzar.com/go/engine
Lesson:
Sorting data is expensive, and
more fields make it worse.
© Brent Ozar Unlimited®. All rights reserved. 19
Download the slides: BrentOzar.com/go/engine
Let’s run it a few times.
SELECT *
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate;
GO 100
Download the slides: BrentOzar.com/go/engine
Your execution plan
1. Shuffle through all of the pages,
writing down all the fields for each record,
if their LastAccessDate > ‘2014/07/01’.
2. Sort the matching records by LastAccessDate.
3. Keep the output so you could reuse it the next
time you saw this same query?
© Brent Ozar Unlimited®. All rights reserved. 20
Download the slides: BrentOzar.com/go/engine
Oracle can.
(One of the reasons it costs $47,000 per core.)
Download the slides: BrentOzar.com/go/engine
Oracle can.
(One of the reasons it costs $47,000 per core.)
Another reason
© Brent Ozar Unlimited®. All rights reserved. 21
Download the slides: BrentOzar.com/go/engine
SQL Server reads & sorts 100 times.
Download the slides: BrentOzar.com/go/engine
Lesson:
SQL Server caches data pages,
not query output.
So how do we
make this fast?
© Brent Ozar Unlimited®. All rights reserved. 22
Download the slides: BrentOzar.com/go/engine
Nonclustered indexes: copies.
Stored in order we want, include the fields we want
CREATE INDEX
IX_LastAccessDate_Id
ON dbo.Users(LastAccessDate, Id)
Download the slides: BrentOzar.com/go/engine
Leaf pages
(we’re focusing on these)
“Index” pages
(but exist for both clustered
and nonclustered indexes)
© Brent Ozar Unlimited®. All rights reserved. 23
Download the slides: BrentOzar.com/go/engine
Let’s go simple again.
SELECT Id
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate;
Download the slides: BrentOzar.com/go/engine
Your execution plan
1. Grab IX_LastAccessDate and seek to
2014/07/01.
2. Read the Id’s out in order.
© Brent Ozar Unlimited®. All rights reserved. 24
Download the slides: BrentOzar.com/go/engine
The new plan uses the index
Download the slides: BrentOzar.com/go/engine
And it’s CHEAP.
© Brent Ozar Unlimited®. All rights reserved. 25
Download the slides: BrentOzar.com/go/engine
SELECT ID SELECT *
No order 6 6
ORDER BY 13 871
ORDER BY, with index <1 48
Download the slides: BrentOzar.com/go/engine
Why cheaper?
For starters, it does
less logical reads…
© Brent Ozar Unlimited®. All rights reserved. 26
Download the slides: BrentOzar.com/go/engine
And less CPU, too.
SET STATISTICS TIME shows
you how much CPU time each
query burned up.
The index eliminates the sort,
which burned up our CPUs.
Download the slides: BrentOzar.com/go/engine
The index covers the fields
needed by the query,
so we call it a covering index.*
*But covering isn’t really a specialkind of index –
it’s only covering when we’re talking about a query.
© Brent Ozar Unlimited®. All rights reserved. 27
Download the slides: BrentOzar.com/go/engine
So nonclustered index seeks
are great, right?
Download the slides: BrentOzar.com/go/engine
“Seek” sounds small, right?
But that’s a lot of data.
© Brent Ozar Unlimited®. All rights reserved. 28
Download the slides: BrentOzar.com/go/engine
You probably think “seek” means,
“I’m going to jump to a row and read that one row.”
You probably think “scan” means,
“I’m going to read the whole thing.”
Download the slides: BrentOzar.com/go/engine
Note that date
“Seek” = read all rows
© Brent Ozar Unlimited®. All rights reserved. 29
Download the slides: BrentOzar.com/go/engine
SQL Server doesn’t know.
You and I know this means the whole table:
But SQL Server doesn’t, and can’t guarantee it
unless you tell it more about the data in the table,
like add a constraint.
(More on that in other classes.)
Download the slides: BrentOzar.com/go/engine
Seek means,
“I’m going to jump to a row and start reading.”
Scan means,
“I’m going to start at either end of the object
(might be either the start, or the end)
and start reading.”
Neither term defines
how many rows will be read.
© Brent Ozar Unlimited®. All rights reserved. 30
Download the slides: BrentOzar.com/go/engine
A scan that reads a few rows:
Download the slides: BrentOzar.com/go/engine
Seeks vs scans
A seek can start at the first row,
and read the entire table.
A scan can start at one end of the table,
and only read a few pages.
We can’t just say, “All index seeks! We’re done.”
© Brent Ozar Unlimited®. All rights reserved. 31
Download the slides: BrentOzar.com/go/engine
Let’s add a couple of fields.
SELECT Id, DisplayName, Age
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate;
Download the slides: BrentOzar.com/go/engine
One execution plan
1. Grab IX_LastAccessDate_Id, seek to 2014/07/01.
2. Write down the Id and LastAccessDate of
matching records.
3. Grab the clustered index (white pages), and look
up each matching row by their Id to get
DisplayName and Age.
© Brent Ozar Unlimited®. All rights reserved. 32
Download the slides: BrentOzar.com/go/engine
Sometimes that
happens, yes.
Download the slides: BrentOzar.com/go/engine
That’s why SQL includes the key
For simplicity, I said I created this index with the Id.
SQL Server always includes your clustering keys
whether you ask for ‘em or not because it has to join
indexes together.
© Brent Ozar Unlimited®. All rights reserved. 33
Download the slides: BrentOzar.com/go/engine
Classic index
tuning sign
Key lookup is required when the
index doesn’t have all the fields
we need.
Hover your mouse over the key
lookup, look for the OUTPUT.
Small fields? Frequently used?
Add ‘em to the index.
Download the slides: BrentOzar.com/go/engine
Sometimes.
<cough>cheated</cough>
© Brent Ozar Unlimited®. All rights reserved. 34
Download the slides: BrentOzar.com/go/engine
But sometimes this happens.
Download the slides: BrentOzar.com/go/engine
Lesson:
Even with indexes,
there’s a tipping point where it’s
more efficient for SQL to just
scan the table once and get out.
© Brent Ozar Unlimited®. All rights reserved. 35
Download the slides: BrentOzar.com/go/engine
Enter statistics.
Download the slides: BrentOzar.com/go/engine
Statistics help SQL Server:
Decide which index to use
What order to process tables/indexes in
Whether to do seeks or scans
Guess how many rows will match your query
How much memory to allocate for the query
© Brent Ozar Unlimited®. All rights reserved. 36
Download the slides: BrentOzar.com/go/engine
Download the slides: BrentOzar.com/go/engine
WHERE LastAccessDate
> '2014/07/01'
Add it up
Add it up
© Brent Ozar Unlimited®. All rights reserved. 37
Download the slides: BrentOzar.com/go/engine
Download the slides: BrentOzar.com/go/engine
Examples of varchar & int stats
© Brent Ozar Unlimited®. All rights reserved. 38
Download the slides: BrentOzar.com/go/engine
Two ways you can help
1. Keep your stats updated at least weekly.
Automatic stats updates aren’t enough. Consider
Ola Hallengren’s free scripts: Ola.Hallengren.com
2. Learn which T-SQL elements will cause cardinality
estimation problems, ignoring statistics
Download the slides: BrentOzar.com/go/engine
One idea, written differently
© Brent Ozar Unlimited®. All rights reserved. 39
Download the slides: BrentOzar.com/go/engine
Estimated 2,076 rows
Estimated 2 rows
Both produce the same 2,443 rows, but
they use 2 different ways to retrieve those
rows due to their different estimates.
Download the slides: BrentOzar.com/go/engine
The classic problem
SQL Server has to decide between:
• Scanning the entire table,
which is great for big data, or
• An index seek + key lookup,
which is better for small data
It bases this decision on
cardinality estimation – and it’s not perfect.
We can avoid this problem by
widening our nonclustered index.
© Brent Ozar Unlimited®. All rights reserved. 40
Download the slides: BrentOzar.com/go/engine
CREATE INDEX IX_LastAccessDate_Id_DisplayName_Age
ON dbo.Users (LastAccessDate, Id, DisplayName, Age)
Or:
CREATE INDEX IX_LastAccessDate_Id_Includes
ON dbo.Users (LastAccessDate, Id)
INCLUDE (DisplayName, Age)
Download the slides: BrentOzar.com/go/engine
Same query again
SELECT Id, DisplayName, Age
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate
© Brent Ozar Unlimited®. All rights reserved. 41
Download the slides: BrentOzar.com/go/engine
Yay! Back to a single operator.
Download the slides: BrentOzar.com/go/engine
Recap
© Brent Ozar Unlimited®. All rights reserved. 42
Download the slides: BrentOzar.com/go/engine
Lessons we learned
SET STATISTICS IO ON: shows # of 8KB pages read
SET STATISTICS TIME ON: shows CPU work done
WHERE without a supporting index: table scan
ORDER BY without a supporting index: CPU work
Indexes reduce page reads and sorts
Seek =! awesome, and scan != terribad
Download the slides: BrentOzar.com/go/engine
Lessons we learned
Index seek + key lookup = we may need wider indexes
Statistics help SQL Server pick indexes, methods
Cardinality estimation isn’t perfect (especially with
real-world T-SQL and joins to multiple tables)
You can help by understanding SQL’s limitations
and crafting your T-SQL to avoid them
Learn more: BrentOzar.com/go/engine

More Related Content

Similar to Geek Sync | How to Think Like the SQL ServerEngine - Brent Ozar

New Repository in AEM 6 by Michael Marth
New Repository in AEM 6 by Michael MarthNew Repository in AEM 6 by Michael Marth
New Repository in AEM 6 by Michael MarthAEM HUB
 
Aem hub oak 0.2 full
Aem hub oak 0.2 fullAem hub oak 0.2 full
Aem hub oak 0.2 fullMichael Marth
 
Jun Heider - Flex Application Profiling By Example
Jun Heider - Flex Application Profiling By ExampleJun Heider - Flex Application Profiling By Example
Jun Heider - Flex Application Profiling By Example360|Conferences
 
Tips for Installing Cognos Analytics: Configuring and Installing the Server
Tips for Installing Cognos Analytics: Configuring and Installing the ServerTips for Installing Cognos Analytics: Configuring and Installing the Server
Tips for Installing Cognos Analytics: Configuring and Installing the ServerSenturus
 
15-ways-to-optimize-spring-boot-for-the-cloud
15-ways-to-optimize-spring-boot-for-the-cloud15-ways-to-optimize-spring-boot-for-the-cloud
15-ways-to-optimize-spring-boot-for-the-cloudBilly Korando
 
Building Secure Services using Containers
Building Secure Services using ContainersBuilding Secure Services using Containers
Building Secure Services using ContainersAmazon Web Services
 
15 ways-to-optimize-spring-boot-for-the-cloud
15 ways-to-optimize-spring-boot-for-the-cloud15 ways-to-optimize-spring-boot-for-the-cloud
15 ways-to-optimize-spring-boot-for-the-cloudPolyglotMeetups
 
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache CalciteEnable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache CalciteChristian Tzolov
 
How to go into production your machine learning models? #CWT2017
How to go into production your machine learning models? #CWT2017How to go into production your machine learning models? #CWT2017
How to go into production your machine learning models? #CWT2017Cloudera Japan
 
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache CalciteEnable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache CalciteVMware Tanzu
 
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil TayarDocker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil TayarApplitools
 
Kickstarting Node.js Projects with Yeoman
Kickstarting Node.js Projects with YeomanKickstarting Node.js Projects with Yeoman
Kickstarting Node.js Projects with YeomanPatrick Buergin
 
Breaking the Monolith road to containers.pdf
Breaking the Monolith road to containers.pdfBreaking the Monolith road to containers.pdf
Breaking the Monolith road to containers.pdfAmazon Web Services
 
Brkucc 3347 troubleshooting-jabber_like_a_tac_engineer
Brkucc 3347 troubleshooting-jabber_like_a_tac_engineerBrkucc 3347 troubleshooting-jabber_like_a_tac_engineer
Brkucc 3347 troubleshooting-jabber_like_a_tac_engineerMichael Ganschuk
 
Tips and tricks in the OSGi Web Console
Tips and tricks in the OSGi Web ConsoleTips and tricks in the OSGi Web Console
Tips and tricks in the OSGi Web ConsoleKevin Nennig
 
Intro to development sites and site migration
Intro to development sites and site migrationIntro to development sites and site migration
Intro to development sites and site migrationR-Cubed Design Forge
 
Frontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser renderingFrontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser renderingManuel Garcia
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesChris Simmonds
 

Similar to Geek Sync | How to Think Like the SQL ServerEngine - Brent Ozar (20)

New Repository in AEM 6 by Michael Marth
New Repository in AEM 6 by Michael MarthNew Repository in AEM 6 by Michael Marth
New Repository in AEM 6 by Michael Marth
 
Aem hub oak 0.2 full
Aem hub oak 0.2 fullAem hub oak 0.2 full
Aem hub oak 0.2 full
 
Jun Heider - Flex Application Profiling By Example
Jun Heider - Flex Application Profiling By ExampleJun Heider - Flex Application Profiling By Example
Jun Heider - Flex Application Profiling By Example
 
Tips for Installing Cognos Analytics: Configuring and Installing the Server
Tips for Installing Cognos Analytics: Configuring and Installing the ServerTips for Installing Cognos Analytics: Configuring and Installing the Server
Tips for Installing Cognos Analytics: Configuring and Installing the Server
 
15-ways-to-optimize-spring-boot-for-the-cloud
15-ways-to-optimize-spring-boot-for-the-cloud15-ways-to-optimize-spring-boot-for-the-cloud
15-ways-to-optimize-spring-boot-for-the-cloud
 
Building Secure Services using Containers
Building Secure Services using ContainersBuilding Secure Services using Containers
Building Secure Services using Containers
 
15 ways-to-optimize-spring-boot-for-the-cloud
15 ways-to-optimize-spring-boot-for-the-cloud15 ways-to-optimize-spring-boot-for-the-cloud
15 ways-to-optimize-spring-boot-for-the-cloud
 
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache CalciteEnable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
 
How to go into production your machine learning models? #CWT2017
How to go into production your machine learning models? #CWT2017How to go into production your machine learning models? #CWT2017
How to go into production your machine learning models? #CWT2017
 
Boston_sql_kegorman_highIO.pptx
Boston_sql_kegorman_highIO.pptxBoston_sql_kegorman_highIO.pptx
Boston_sql_kegorman_highIO.pptx
 
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache CalciteEnable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
Enable SQL/JDBC Access to Apache Geode/GemFire Using Apache Calcite
 
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil TayarDocker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
 
Kickstarting Node.js Projects with Yeoman
Kickstarting Node.js Projects with YeomanKickstarting Node.js Projects with Yeoman
Kickstarting Node.js Projects with Yeoman
 
Big datademo
Big datademoBig datademo
Big datademo
 
Breaking the Monolith road to containers.pdf
Breaking the Monolith road to containers.pdfBreaking the Monolith road to containers.pdf
Breaking the Monolith road to containers.pdf
 
Brkucc 3347 troubleshooting-jabber_like_a_tac_engineer
Brkucc 3347 troubleshooting-jabber_like_a_tac_engineerBrkucc 3347 troubleshooting-jabber_like_a_tac_engineer
Brkucc 3347 troubleshooting-jabber_like_a_tac_engineer
 
Tips and tricks in the OSGi Web Console
Tips and tricks in the OSGi Web ConsoleTips and tricks in the OSGi Web Console
Tips and tricks in the OSGi Web Console
 
Intro to development sites and site migration
Intro to development sites and site migrationIntro to development sites and site migration
Intro to development sites and site migration
 
Frontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser renderingFrontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser rendering
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot images
 

More from IDERA Software

The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...IDERA Software
 
Problems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloudProblems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloudIDERA Software
 
Public cloud uses and limitations
Public cloud uses and limitationsPublic cloud uses and limitations
Public cloud uses and limitationsIDERA Software
 
Optimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptxOptimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptxIDERA Software
 
Monitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL ServerMonitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL ServerIDERA Software
 
Database administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databasesDatabase administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databasesIDERA Software
 
Six tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costsSix tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costsIDERA Software
 
Idera live 2021: The Power of Abstraction by Steve Hoberman
Idera live 2021:  The Power of Abstraction by Steve HobermanIdera live 2021:  The Power of Abstraction by Steve Hoberman
Idera live 2021: The Power of Abstraction by Steve HobermanIDERA Software
 
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian Flug
Idera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian FlugIdera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian Flug
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian FlugIDERA Software
 
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...IDERA Software
 
Idera live 2021: Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021:  Managing Digital Transformation on a Budget by Bert ScalzoIdera live 2021:  Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021: Managing Digital Transformation on a Budget by Bert ScalzoIDERA Software
 
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...IDERA Software
 
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...IDERA Software
 
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...IDERA Software
 
Idera live 2021: Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021:  Performance Tuning Azure SQL Database by Monica RathbunIdera live 2021:  Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021: Performance Tuning Azure SQL Database by Monica RathbunIDERA Software
 
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERAGeek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERAIDERA Software
 
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...IDERA Software
 
Benefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERABenefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERAIDERA Software
 
Achieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERAAchieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERAIDERA Software
 
Benefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERABenefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERAIDERA Software
 

More from IDERA Software (20)

The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...
 
Problems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloudProblems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloud
 
Public cloud uses and limitations
Public cloud uses and limitationsPublic cloud uses and limitations
Public cloud uses and limitations
 
Optimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptxOptimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptx
 
Monitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL ServerMonitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL Server
 
Database administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databasesDatabase administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databases
 
Six tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costsSix tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costs
 
Idera live 2021: The Power of Abstraction by Steve Hoberman
Idera live 2021:  The Power of Abstraction by Steve HobermanIdera live 2021:  The Power of Abstraction by Steve Hoberman
Idera live 2021: The Power of Abstraction by Steve Hoberman
 
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian Flug
Idera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian FlugIdera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian Flug
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian Flug
 
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
 
Idera live 2021: Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021:  Managing Digital Transformation on a Budget by Bert ScalzoIdera live 2021:  Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021: Managing Digital Transformation on a Budget by Bert Scalzo
 
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
 
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...
 
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...
 
Idera live 2021: Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021:  Performance Tuning Azure SQL Database by Monica RathbunIdera live 2021:  Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021: Performance Tuning Azure SQL Database by Monica Rathbun
 
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERAGeek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
 
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
 
Benefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERABenefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERA
 
Achieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERAAchieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERA
 
Benefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERABenefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERA
 

Recently uploaded

Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 

Recently uploaded (20)

Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 

Geek Sync | How to Think Like the SQL ServerEngine - Brent Ozar

  • 1. © Brent Ozar Unlimited®. All rights reserved. 1 Download the slides: BrentOzar.com/go/engine How to Think Like the SQL Server Engine BrentOzar.com/go/engine Download the slides: BrentOzar.com/go/engine We’re using Stack Overflow data. Open source, licensed with Creative Commons SQL Server: BrentOzar.com/go/querystack XML dump: archive.org/details/stackexchange I’m using SQL Server 2019, compatibility level 150/2019. My cost threshold for parallelism is 5.
  • 2. © Brent Ozar Unlimited®. All rights reserved. 2 Download the slides: BrentOzar.com/go/engine Download the slides: BrentOzar.com/go/engine
  • 3. © Brent Ozar Unlimited®. All rights reserved. 3 Download the slides: BrentOzar.com/go/engine Download the slides: BrentOzar.com/go/engine Page Header Index OR Data Rows Slot Array 8KB
  • 4. © Brent Ozar Unlimited®. All rights reserved. 4 Download the slides: BrentOzar.com/go/engine You: SQL Server. Me: end user. Download the slides: BrentOzar.com/go/engine First query: SELECT Id FROM dbo.Users
  • 5. © Brent Ozar Unlimited®. All rights reserved. 5 Download the slides: BrentOzar.com/go/engine Your execution plan: 1. Shuffle through all of the pages, saying the Id of each record out loud. Download the slides: BrentOzar.com/go/engine SQL Server’s execution plan
  • 6. © Brent Ozar Unlimited®. All rights reserved. 6 Download the slides: BrentOzar.com/go/engine SET STATISTICS IO ON Logical reads: the number of 8K pages we read. (7,405 x 8KB = 59MB) Download the slides: BrentOzar.com/go/engine That’s 15 reams.
  • 7. © Brent Ozar Unlimited®. All rights reserved. 7 Download the slides: BrentOzar.com/go/engine Let’s add a filter. SELECT Id FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ Download the slides: BrentOzar.com/go/engine Your execution plan: 1. Shuffle through all of the pages, saying the Id of each record out loud, if their LastAccessDate > ‘2014/07/01’.
  • 8. © Brent Ozar Unlimited®. All rights reserved. 8 Download the slides: BrentOzar.com/go/engine SQL Server’s execution plan Download the slides: BrentOzar.com/go/engine
  • 9. © Brent Ozar Unlimited®. All rights reserved. 9 Download the slides: BrentOzar.com/go/engine Lesson: Using WHERE without a matching index means scanning all the data. (Andtherearesomeextrareadswhenqueriesgoparallel –butmoreonthatinourmoreadvancedclasses.) Download the slides: BrentOzar.com/go/engine
  • 10. © Brent Ozar Unlimited®. All rights reserved. 10 Download the slides: BrentOzar.com/go/engine Download the slides: BrentOzar.com/go/engine Lesson: Estimated Subtree Cost is a rough measure of CPU and IO work required for a query.
  • 11. © Brent Ozar Unlimited®. All rights reserved. 11 Download the slides: BrentOzar.com/go/engine Let’s add a sort. SELECT Id FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate Download the slides: BrentOzar.com/go/engine Your execution plan 1. Shuffle through all of the pages, writing down fields __________ for each record, if their LastAccessDate > ‘2014/07/01’. 2. Sort the matching records by LastAccessDate.
  • 12. © Brent Ozar Unlimited®. All rights reserved. 12 Download the slides: BrentOzar.com/go/engine SQL Server’s execution plan Download the slides: BrentOzar.com/go/engine
  • 13. © Brent Ozar Unlimited®. All rights reserved. 13 Download the slides: BrentOzar.com/go/engine Order By: Cost is up about 2x We needed space to write down our results, so we got a memory grant Download the slides: BrentOzar.com/go/engine You can see more in Properties
  • 14. © Brent Ozar Unlimited®. All rights reserved. 14 Download the slides: BrentOzar.com/go/engine You can’t always get what you want. Memory is set when the query starts, and not revised. SQL Server has to assume other people will run queries at the same time as you. Your memory grant can change with each time that you run a query. * - This screenshot is froma different query toshowvariances. Download the slides: BrentOzar.com/go/engine And if you run out of memory…
  • 15. © Brent Ozar Unlimited®. All rights reserved. 15 Download the slides: BrentOzar.com/go/engine Let’s get all the fields. SELECT * FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate Download the slides: BrentOzar.com/go/engine Your execution plan 1. Shuffle through all of the pages, writing down fields __________ for each record, if their LastAccessDate > ‘2014/07/01’. 2. Sort the matching records by LastAccessDate.
  • 16. © Brent Ozar Unlimited®. All rights reserved. 16 Download the slides: BrentOzar.com/go/engine That query sucks. Download the slides: BrentOzar.com/go/engine But why does it suck? Do we work harder to read the data? Do we work harder to write the data? Do we work harder to sort the data? Do we work harder to output the data?
  • 17. © Brent Ozar Unlimited®. All rights reserved. 17 Download the slides: BrentOzar.com/go/engine The sort cost is now 97%... Download the slides: BrentOzar.com/go/engine Of a MUCH larger overall cost.
  • 18. © Brent Ozar Unlimited®. All rights reserved. 18 Download the slides: BrentOzar.com/go/engine SELECT ID SELECT * No order 6 6 ORDER BY 13 871 Download the slides: BrentOzar.com/go/engine Lesson: Sorting data is expensive, and more fields make it worse.
  • 19. © Brent Ozar Unlimited®. All rights reserved. 19 Download the slides: BrentOzar.com/go/engine Let’s run it a few times. SELECT * FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate; GO 100 Download the slides: BrentOzar.com/go/engine Your execution plan 1. Shuffle through all of the pages, writing down all the fields for each record, if their LastAccessDate > ‘2014/07/01’. 2. Sort the matching records by LastAccessDate. 3. Keep the output so you could reuse it the next time you saw this same query?
  • 20. © Brent Ozar Unlimited®. All rights reserved. 20 Download the slides: BrentOzar.com/go/engine Oracle can. (One of the reasons it costs $47,000 per core.) Download the slides: BrentOzar.com/go/engine Oracle can. (One of the reasons it costs $47,000 per core.) Another reason
  • 21. © Brent Ozar Unlimited®. All rights reserved. 21 Download the slides: BrentOzar.com/go/engine SQL Server reads & sorts 100 times. Download the slides: BrentOzar.com/go/engine Lesson: SQL Server caches data pages, not query output. So how do we make this fast?
  • 22. © Brent Ozar Unlimited®. All rights reserved. 22 Download the slides: BrentOzar.com/go/engine Nonclustered indexes: copies. Stored in order we want, include the fields we want CREATE INDEX IX_LastAccessDate_Id ON dbo.Users(LastAccessDate, Id) Download the slides: BrentOzar.com/go/engine Leaf pages (we’re focusing on these) “Index” pages (but exist for both clustered and nonclustered indexes)
  • 23. © Brent Ozar Unlimited®. All rights reserved. 23 Download the slides: BrentOzar.com/go/engine Let’s go simple again. SELECT Id FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate; Download the slides: BrentOzar.com/go/engine Your execution plan 1. Grab IX_LastAccessDate and seek to 2014/07/01. 2. Read the Id’s out in order.
  • 24. © Brent Ozar Unlimited®. All rights reserved. 24 Download the slides: BrentOzar.com/go/engine The new plan uses the index Download the slides: BrentOzar.com/go/engine And it’s CHEAP.
  • 25. © Brent Ozar Unlimited®. All rights reserved. 25 Download the slides: BrentOzar.com/go/engine SELECT ID SELECT * No order 6 6 ORDER BY 13 871 ORDER BY, with index <1 48 Download the slides: BrentOzar.com/go/engine Why cheaper? For starters, it does less logical reads…
  • 26. © Brent Ozar Unlimited®. All rights reserved. 26 Download the slides: BrentOzar.com/go/engine And less CPU, too. SET STATISTICS TIME shows you how much CPU time each query burned up. The index eliminates the sort, which burned up our CPUs. Download the slides: BrentOzar.com/go/engine The index covers the fields needed by the query, so we call it a covering index.* *But covering isn’t really a specialkind of index – it’s only covering when we’re talking about a query.
  • 27. © Brent Ozar Unlimited®. All rights reserved. 27 Download the slides: BrentOzar.com/go/engine So nonclustered index seeks are great, right? Download the slides: BrentOzar.com/go/engine “Seek” sounds small, right? But that’s a lot of data.
  • 28. © Brent Ozar Unlimited®. All rights reserved. 28 Download the slides: BrentOzar.com/go/engine You probably think “seek” means, “I’m going to jump to a row and read that one row.” You probably think “scan” means, “I’m going to read the whole thing.” Download the slides: BrentOzar.com/go/engine Note that date “Seek” = read all rows
  • 29. © Brent Ozar Unlimited®. All rights reserved. 29 Download the slides: BrentOzar.com/go/engine SQL Server doesn’t know. You and I know this means the whole table: But SQL Server doesn’t, and can’t guarantee it unless you tell it more about the data in the table, like add a constraint. (More on that in other classes.) Download the slides: BrentOzar.com/go/engine Seek means, “I’m going to jump to a row and start reading.” Scan means, “I’m going to start at either end of the object (might be either the start, or the end) and start reading.” Neither term defines how many rows will be read.
  • 30. © Brent Ozar Unlimited®. All rights reserved. 30 Download the slides: BrentOzar.com/go/engine A scan that reads a few rows: Download the slides: BrentOzar.com/go/engine Seeks vs scans A seek can start at the first row, and read the entire table. A scan can start at one end of the table, and only read a few pages. We can’t just say, “All index seeks! We’re done.”
  • 31. © Brent Ozar Unlimited®. All rights reserved. 31 Download the slides: BrentOzar.com/go/engine Let’s add a couple of fields. SELECT Id, DisplayName, Age FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate; Download the slides: BrentOzar.com/go/engine One execution plan 1. Grab IX_LastAccessDate_Id, seek to 2014/07/01. 2. Write down the Id and LastAccessDate of matching records. 3. Grab the clustered index (white pages), and look up each matching row by their Id to get DisplayName and Age.
  • 32. © Brent Ozar Unlimited®. All rights reserved. 32 Download the slides: BrentOzar.com/go/engine Sometimes that happens, yes. Download the slides: BrentOzar.com/go/engine That’s why SQL includes the key For simplicity, I said I created this index with the Id. SQL Server always includes your clustering keys whether you ask for ‘em or not because it has to join indexes together.
  • 33. © Brent Ozar Unlimited®. All rights reserved. 33 Download the slides: BrentOzar.com/go/engine Classic index tuning sign Key lookup is required when the index doesn’t have all the fields we need. Hover your mouse over the key lookup, look for the OUTPUT. Small fields? Frequently used? Add ‘em to the index. Download the slides: BrentOzar.com/go/engine Sometimes. <cough>cheated</cough>
  • 34. © Brent Ozar Unlimited®. All rights reserved. 34 Download the slides: BrentOzar.com/go/engine But sometimes this happens. Download the slides: BrentOzar.com/go/engine Lesson: Even with indexes, there’s a tipping point where it’s more efficient for SQL to just scan the table once and get out.
  • 35. © Brent Ozar Unlimited®. All rights reserved. 35 Download the slides: BrentOzar.com/go/engine Enter statistics. Download the slides: BrentOzar.com/go/engine Statistics help SQL Server: Decide which index to use What order to process tables/indexes in Whether to do seeks or scans Guess how many rows will match your query How much memory to allocate for the query
  • 36. © Brent Ozar Unlimited®. All rights reserved. 36 Download the slides: BrentOzar.com/go/engine Download the slides: BrentOzar.com/go/engine WHERE LastAccessDate > '2014/07/01' Add it up Add it up
  • 37. © Brent Ozar Unlimited®. All rights reserved. 37 Download the slides: BrentOzar.com/go/engine Download the slides: BrentOzar.com/go/engine Examples of varchar & int stats
  • 38. © Brent Ozar Unlimited®. All rights reserved. 38 Download the slides: BrentOzar.com/go/engine Two ways you can help 1. Keep your stats updated at least weekly. Automatic stats updates aren’t enough. Consider Ola Hallengren’s free scripts: Ola.Hallengren.com 2. Learn which T-SQL elements will cause cardinality estimation problems, ignoring statistics Download the slides: BrentOzar.com/go/engine One idea, written differently
  • 39. © Brent Ozar Unlimited®. All rights reserved. 39 Download the slides: BrentOzar.com/go/engine Estimated 2,076 rows Estimated 2 rows Both produce the same 2,443 rows, but they use 2 different ways to retrieve those rows due to their different estimates. Download the slides: BrentOzar.com/go/engine The classic problem SQL Server has to decide between: • Scanning the entire table, which is great for big data, or • An index seek + key lookup, which is better for small data It bases this decision on cardinality estimation – and it’s not perfect. We can avoid this problem by widening our nonclustered index.
  • 40. © Brent Ozar Unlimited®. All rights reserved. 40 Download the slides: BrentOzar.com/go/engine CREATE INDEX IX_LastAccessDate_Id_DisplayName_Age ON dbo.Users (LastAccessDate, Id, DisplayName, Age) Or: CREATE INDEX IX_LastAccessDate_Id_Includes ON dbo.Users (LastAccessDate, Id) INCLUDE (DisplayName, Age) Download the slides: BrentOzar.com/go/engine Same query again SELECT Id, DisplayName, Age FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate
  • 41. © Brent Ozar Unlimited®. All rights reserved. 41 Download the slides: BrentOzar.com/go/engine Yay! Back to a single operator. Download the slides: BrentOzar.com/go/engine Recap
  • 42. © Brent Ozar Unlimited®. All rights reserved. 42 Download the slides: BrentOzar.com/go/engine Lessons we learned SET STATISTICS IO ON: shows # of 8KB pages read SET STATISTICS TIME ON: shows CPU work done WHERE without a supporting index: table scan ORDER BY without a supporting index: CPU work Indexes reduce page reads and sorts Seek =! awesome, and scan != terribad Download the slides: BrentOzar.com/go/engine Lessons we learned Index seek + key lookup = we may need wider indexes Statistics help SQL Server pick indexes, methods Cardinality estimation isn’t perfect (especially with real-world T-SQL and joins to multiple tables) You can help by understanding SQL’s limitations and crafting your T-SQL to avoid them Learn more: BrentOzar.com/go/engine