SlideShare una empresa de Scribd logo
1 de 93
Intro to Internals
How to Think Like the SQL Engine
Brent Ozar, Brent Ozar Unlimited
MIT License
Copyright © 2016 Brent Ozar.
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to
whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
I know, I hate killing trees.
But having these next 3 pages in your hand will help a lot
as we talk through the demos.
Print this 3-page PDF to follow along:
http://u.BrentOzar.com/engine.pdf
3
Brent Ozar
Consultant, Brent Ozar Unlimited
I make SQL Server faster and more reliable.
I created sp_Blitz® and the SQL Server First
Responder Kit, and I loves sharing knowledge at
BrentOzar.com. I hold a bunch of certifications and
awards including the rare Microsoft Certified Master.
You don’t care about any of that though.
Download the PDF: BrentOzar.com/go/enginepdf
/brentozar @brento brentozar
Agenda
When you pass in a query, how does SQL Server build the results? Time
to role play: Brent will be an end user sending in queries, and you will
play the part of the SQL Server engine. Using simple spreadsheets as
your tables, you will learn how SQL Server builds execution plans,
uses indexes, performs joins, and considers statistics.
This session is for DBAs and developers who are comfortable writing
queries, but not so comfortable when it comes to explaining
nonclustered indexes, lookups, sargability, fill factor, and corruption
detection.
Index OR
Data Rows
Slot Array
8KB
Page header
Leaf pages
Index
pages
You: SQL Server.
Me: end user.
First query:
SELECT Id
FROM dbo.Users
Your execution plan:
1. Shuffle through all of the pages,
saying the Id of each record out loud.
SQL Server’s execution plan
SET STATISTICS IO ON
Logical reads:
the number of 8K pages we read.
(79,672 x 8KB = 637MB)
That’s 159 reams.
Let’s add a filter.
SELECT Id
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
Your execution plan:
1. Shuffle through all of the pages,
saying the Id of each record out loud,
if their LastAccessDate > ‘2014/07/01’.
SQL Server’s execution plan
Lesson:
Using a WHERE without a
matching index means
scanning all the data.
Lesson:
Estimated Subtree Cost
guesses at CPU and IO
work required for a query.
Let’s add a sort.
SELECT Id
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate
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.
SQL Server’s execution plan
Cost is up ~4x
We needed space to
write down our results,
so we got a memory grant
Order By:
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.
You can’t always get
what you want.
And if you run out of memory…
Let’s get all the fields.
SELECT *
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate
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.
Lesson:
SELECT * sucks.
But let’s dig deeper.
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?
SQL Server’s execution plan
SELECT ID SELECT *
No order 66 66
ORDER BY 259 20,666
Lesson:
Sorting is expensive,
and more fields
makes it worse.
Let’s run it a few times.
SELECT *
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate;
GO 5
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?
Oracle can.
(It better, since it costs
$47,000 per core.)
SQL Server reads & sorts 5 times.
Lesson:
SQL Server caches raw data
pages, not output.
Nonclustered indexes: copies.
Stored in the order we want
Include the fields we want
CREATE INDEX
IX_LastAccessDate_Id
ON dbo.Users(LastAccessDate, Id)
Let’s go simple again.
SELECT Id
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate;
Your execution plan
1. Grab IX_LastAccessDate and seek to 2014/07/01.
2. Read the Id’s out in order.
SQL Server’s execution plan
SELECT ID SELECT *
No order 66 66
ORDER BY 259 20,666
ORDER BY
(with index)
10 6,354
Lesson:
Indexes reduce reads.
Duh.
Lesson:
Indexes also
reduce CPU time.
Yes, this is a “seek.”
Don’t think scan = terrible.
It covers the fields we need in this query.
But if we change the query…
That’s a covering index.
Let’s add a couple of fields.
SELECT Id, DisplayName, Age
FROM dbo.Users
WHERE LastAccessDate > ‘2014/07/01’
ORDER BY LastAccessDate;
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.
The SQL Server equivalent
For simplicity, I told you 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.
That’s why SQL Server includes the key
Key lookup is required
when the index doesn’t
have all the fields we need.
Hover your mouse over the
key lookup and look for the
OUTPUT fields.
Small? Frequently used?
Add ‘em to the index.
DO NOT ADD A NEW INDEX.
Classic index
tuning sign
But to get that plan, I had to cheat.
Because with 2014/07/01, I get:
Lesson:
Even with indexes,
there’s a tipping point
where scans work better.
Enter statistics.
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
Statistics help SQL Server:
WHERE LastAccessDate > ‘2014/07/01’
Add it up, add it up
Automatic stats updates aren’t enough. Consider:
• http://Ola.Hallengren.com
• http://MinionWare.net/reindex
Typical strategy: weekly statistics updates
Updated statistics on an index invalidate query plans that
involve that index
• Affects your plan cache analysis
• Can cause unpredictable query plan changes
Keep statistics updated.
How about on a single random date?
Let’s write it differently.
Wait – what?
Why can’t I get just one row
Lesson:
This is called
Cardinality Estimation,
and it’s not just about
keeping stats updated.
The Cardinality Estimator has huge improvements.
To turn ‘em on, just change your Compatibility Level.
Fortunately, SQL 2014/2016 fixes this.
And run the exact same query again
All better!
Lesson:
2014/2016’s new
Cardinality Estimator
is, uh, new
Let’s add a join.
Lesson:
bad cardinality estimation
is at the dark heart
of many bad plans.
Whew.
That’s a lot of lessons.
Clustered indexes hold all the fields*
Nonclustered indexes are light-weight* copies of the table
NC indexes reduce not just reads, but also CPU work
SQL Server caches raw data pages, not query output
Statistics drive seek vs scan, index choice, memory
Statistics aren’t the only part: cardinality estimation matters
Includes and seeks aren’t magically delicious
What we learned
Thank You
Learn more from
Brent Ozar
help@brentozar.com or follow @BrentO

Más contenido relacionado

La actualidad más candente

SSD Deployment Strategies for MySQL
SSD Deployment Strategies for MySQLSSD Deployment Strategies for MySQL
SSD Deployment Strategies for MySQLYoshinori Matsunobu
 
InnoDB Performance Optimisation
InnoDB Performance OptimisationInnoDB Performance Optimisation
InnoDB Performance OptimisationMydbops
 
MySQL Timeout Variables Explained
MySQL Timeout Variables Explained MySQL Timeout Variables Explained
MySQL Timeout Variables Explained Mydbops
 
MySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 TipsMySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 TipsOSSCube
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performancePostgreSQL-Consulting
 
Redefining tables online without surprises
Redefining tables online without surprisesRedefining tables online without surprises
Redefining tables online without surprisesNelson Calero
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 
Optimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceOptimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceMariaDB plc
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Alexey Lesovsky
 
Linux Memory Management with CMA (Contiguous Memory Allocator)
Linux Memory Management with CMA (Contiguous Memory Allocator)Linux Memory Management with CMA (Contiguous Memory Allocator)
Linux Memory Management with CMA (Contiguous Memory Allocator)Pankaj Suryawanshi
 
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11Federico Razzoli
 
MySQL Performance Schema in MySQL 8.0
MySQL Performance Schema in MySQL 8.0MySQL Performance Schema in MySQL 8.0
MySQL Performance Schema in MySQL 8.0Mayank Prasad
 
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLTop 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLJim Mlodgenski
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index CookbookMYXPLAIN
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBMydbops
 
Advanced MySQL Query Tuning
Advanced MySQL Query TuningAdvanced MySQL Query Tuning
Advanced MySQL Query TuningAlexander Rubin
 
How Safe is Asynchronous Master-Master Setup?
 How Safe is Asynchronous Master-Master Setup? How Safe is Asynchronous Master-Master Setup?
How Safe is Asynchronous Master-Master Setup?Sveta Smirnova
 

La actualidad más candente (20)

SSD Deployment Strategies for MySQL
SSD Deployment Strategies for MySQLSSD Deployment Strategies for MySQL
SSD Deployment Strategies for MySQL
 
InnoDB Performance Optimisation
InnoDB Performance OptimisationInnoDB Performance Optimisation
InnoDB Performance Optimisation
 
MySQL Timeout Variables Explained
MySQL Timeout Variables Explained MySQL Timeout Variables Explained
MySQL Timeout Variables Explained
 
MySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 TipsMySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 Tips
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performance
 
Linux Memory
Linux MemoryLinux Memory
Linux Memory
 
Redefining tables online without surprises
Redefining tables online without surprisesRedefining tables online without surprises
Redefining tables online without surprises
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Optimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performanceOptimizing MariaDB for maximum performance
Optimizing MariaDB for maximum performance
 
Redo log
Redo logRedo log
Redo log
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.
 
Linux Memory Management with CMA (Contiguous Memory Allocator)
Linux Memory Management with CMA (Contiguous Memory Allocator)Linux Memory Management with CMA (Contiguous Memory Allocator)
Linux Memory Management with CMA (Contiguous Memory Allocator)
 
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
Webinar - Key Reasons to Upgrade to MySQL 8.0 or MariaDB 10.11
 
MySQL Performance Schema in MySQL 8.0
MySQL Performance Schema in MySQL 8.0MySQL Performance Schema in MySQL 8.0
MySQL Performance Schema in MySQL 8.0
 
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLTop 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
 
MySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB StatusMySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB Status
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
 
Advanced MySQL Query Tuning
Advanced MySQL Query TuningAdvanced MySQL Query Tuning
Advanced MySQL Query Tuning
 
How Safe is Asynchronous Master-Master Setup?
 How Safe is Asynchronous Master-Master Setup? How Safe is Asynchronous Master-Master Setup?
How Safe is Asynchronous Master-Master Setup?
 

Destacado

500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career InternalsBrent Ozar
 
500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career InternalsBrent Ozar
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql serverDivya Sharma
 
What's new in SQL Server 2016
What's new in SQL Server 2016What's new in SQL Server 2016
What's new in SQL Server 2016James Serra
 
SQL Server on Linux - march 2017
SQL Server on Linux - march 2017SQL Server on Linux - march 2017
SQL Server on Linux - march 2017Sorin Peste
 
Building a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura RelativityBuilding a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura RelativityBrent Ozar
 
What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015Brent Ozar
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureKevin Kline
 
How to Make SQL Server Go Faster
How to Make SQL Server Go FasterHow to Make SQL Server Go Faster
How to Make SQL Server Go FasterBrent Ozar
 
Business Continuity Management for Libraries
Business Continuity Management for LibrariesBusiness Continuity Management for Libraries
Business Continuity Management for LibrariesBoonlert Aroonpiboon
 
Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2
Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2
Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2Bala Subra
 
Reports with SQL Server Reporting Services
Reports with SQL Server Reporting ServicesReports with SQL Server Reporting Services
Reports with SQL Server Reporting ServicesPeter Gfader
 
The Globalization of Technical Writing - Threat or Opportunity
The Globalization of Technical Writing - Threat or OpportunityThe Globalization of Technical Writing - Threat or Opportunity
The Globalization of Technical Writing - Threat or OpportunitySaiff Solutions, Inc.
 
VMworld 2015: Advanced SQL Server on vSphere
VMworld 2015: Advanced SQL Server on vSphereVMworld 2015: Advanced SQL Server on vSphere
VMworld 2015: Advanced SQL Server on vSphereVMworld
 
Microsoft SQL Server - BI Consolidation Presentation
Microsoft SQL Server - BI Consolidation PresentationMicrosoft SQL Server - BI Consolidation Presentation
Microsoft SQL Server - BI Consolidation PresentationMicrosoft Private Cloud
 
SQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
SQL Server AlwaysOn for Dummies SQLSaturday #202 EditionSQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
SQL Server AlwaysOn for Dummies SQLSaturday #202 EditionMark Broadbent
 
SQL Server 2016 New Features and Enhancements
SQL Server 2016 New Features and EnhancementsSQL Server 2016 New Features and Enhancements
SQL Server 2016 New Features and EnhancementsJohn Martin
 

Destacado (20)

500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career Internals
 
500-Level Guide to Career Internals
500-Level Guide to Career Internals500-Level Guide to Career Internals
500-Level Guide to Career Internals
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql server
 
What's new in SQL Server 2016
What's new in SQL Server 2016What's new in SQL Server 2016
What's new in SQL Server 2016
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
SQL Server on Linux - march 2017
SQL Server on Linux - march 2017SQL Server on Linux - march 2017
SQL Server on Linux - march 2017
 
Building a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura RelativityBuilding a Fast, Reliable SQL Server for kCura Relativity
Building a Fast, Reliable SQL Server for kCura Relativity
 
What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015What I Learned About SQL Server at Ignite 2015
What I Learned About SQL Server at Ignite 2015
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
 
How to Make SQL Server Go Faster
How to Make SQL Server Go FasterHow to Make SQL Server Go Faster
How to Make SQL Server Go Faster
 
SqlSaturday199 - Columnstore Indexes
SqlSaturday199 - Columnstore IndexesSqlSaturday199 - Columnstore Indexes
SqlSaturday199 - Columnstore Indexes
 
Business Continuity Management for Libraries
Business Continuity Management for LibrariesBusiness Continuity Management for Libraries
Business Continuity Management for Libraries
 
Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2
Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2
Basics & Intro to SQL Server Reporting Services: Sql Server Ssrs 2008 R2
 
Reports with SQL Server Reporting Services
Reports with SQL Server Reporting ServicesReports with SQL Server Reporting Services
Reports with SQL Server Reporting Services
 
The Globalization of Technical Writing - Threat or Opportunity
The Globalization of Technical Writing - Threat or OpportunityThe Globalization of Technical Writing - Threat or Opportunity
The Globalization of Technical Writing - Threat or Opportunity
 
SQL Server High Availability
SQL Server High AvailabilitySQL Server High Availability
SQL Server High Availability
 
VMworld 2015: Advanced SQL Server on vSphere
VMworld 2015: Advanced SQL Server on vSphereVMworld 2015: Advanced SQL Server on vSphere
VMworld 2015: Advanced SQL Server on vSphere
 
Microsoft SQL Server - BI Consolidation Presentation
Microsoft SQL Server - BI Consolidation PresentationMicrosoft SQL Server - BI Consolidation Presentation
Microsoft SQL Server - BI Consolidation Presentation
 
SQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
SQL Server AlwaysOn for Dummies SQLSaturday #202 EditionSQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
SQL Server AlwaysOn for Dummies SQLSaturday #202 Edition
 
SQL Server 2016 New Features and Enhancements
SQL Server 2016 New Features and EnhancementsSQL Server 2016 New Features and Enhancements
SQL Server 2016 New Features and Enhancements
 

Similar a Introduction to SQL Server Internals: How to Think Like the Engine

How to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineHow to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineBrent Ozar
 
Sql interview question part 9
Sql interview question part 9Sql interview question part 9
Sql interview question part 9kaashiv1
 
Sql interview-question-part-9
Sql interview-question-part-9Sql interview-question-part-9
Sql interview-question-part-9kaashiv1
 
Sql interview question part 6
Sql interview question part 6Sql interview question part 6
Sql interview question part 6kaashiv1
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6kaashiv1
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6kaashiv1
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8kaashiv1
 
Managing SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAManaging SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAConcentrated Technology
 
Kaashiv SQL Server Interview Questions Presentation
Kaashiv SQL Server Interview Questions PresentationKaashiv SQL Server Interview Questions Presentation
Kaashiv SQL Server Interview Questions Presentationkaashiv1
 
Sql server 2012 tutorials writing transact-sql statements
Sql server 2012 tutorials   writing transact-sql statementsSql server 2012 tutorials   writing transact-sql statements
Sql server 2012 tutorials writing transact-sql statementsSteve Xu
 
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresDynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresBrent Ozar
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptxKareemBullard1
 
KoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginnersKoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginnersTobias Koprowski
 
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginnersKoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginnersTobias Koprowski
 

Similar a Introduction to SQL Server Internals: How to Think Like the Engine (20)

How to Think Like the SQL Server Engine
How to Think Like the SQL Server EngineHow to Think Like the SQL Server Engine
How to Think Like the SQL Server Engine
 
Ebook9
Ebook9Ebook9
Ebook9
 
Sql interview question part 9
Sql interview question part 9Sql interview question part 9
Sql interview question part 9
 
Ebook9
Ebook9Ebook9
Ebook9
 
Sql interview-question-part-9
Sql interview-question-part-9Sql interview-question-part-9
Sql interview-question-part-9
 
Ebook6
Ebook6Ebook6
Ebook6
 
Sql interview question part 6
Sql interview question part 6Sql interview question part 6
Sql interview question part 6
 
Ebook6
Ebook6Ebook6
Ebook6
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8
 
Ebook8
Ebook8Ebook8
Ebook8
 
Managing SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAManaging SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBA
 
Ebook11
Ebook11Ebook11
Ebook11
 
Kaashiv SQL Server Interview Questions Presentation
Kaashiv SQL Server Interview Questions PresentationKaashiv SQL Server Interview Questions Presentation
Kaashiv SQL Server Interview Questions Presentation
 
Sql server 2012 tutorials writing transact-sql statements
Sql server 2012 tutorials   writing transact-sql statementsSql server 2012 tutorials   writing transact-sql statements
Sql server 2012 tutorials writing transact-sql statements
 
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresDynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
 
KoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginnersKoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginners
 
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginnersKoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
 

Más de Brent Ozar

Fundamentals of TempDB
Fundamentals of TempDBFundamentals of TempDB
Fundamentals of TempDBBrent Ozar
 
Fundamentals of Columnstore - Introductions
Fundamentals of Columnstore - IntroductionsFundamentals of Columnstore - Introductions
Fundamentals of Columnstore - IntroductionsBrent Ozar
 
Top 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL ServerTop 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL ServerBrent Ozar
 
Deadlocks: Lets Do One, Understand It, and Fix It
Deadlocks: Lets Do One, Understand It, and Fix ItDeadlocks: Lets Do One, Understand It, and Fix It
Deadlocks: Lets Do One, Understand It, and Fix ItBrent Ozar
 
Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!Brent Ozar
 
An Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarAn Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarBrent Ozar
 
SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?Brent Ozar
 
Headaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and DeadlockingHeadaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and DeadlockingBrent Ozar
 
"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server Problems"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server ProblemsBrent Ozar
 
Columnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil AgarwalColumnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil AgarwalBrent Ozar
 

Más de Brent Ozar (10)

Fundamentals of TempDB
Fundamentals of TempDBFundamentals of TempDB
Fundamentals of TempDB
 
Fundamentals of Columnstore - Introductions
Fundamentals of Columnstore - IntroductionsFundamentals of Columnstore - Introductions
Fundamentals of Columnstore - Introductions
 
Top 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL ServerTop 10 Developer Mistakes That Won't Scale with SQL Server
Top 10 Developer Mistakes That Won't Scale with SQL Server
 
Deadlocks: Lets Do One, Understand It, and Fix It
Deadlocks: Lets Do One, Understand It, and Fix ItDeadlocks: Lets Do One, Understand It, and Fix It
Deadlocks: Lets Do One, Understand It, and Fix It
 
Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!Help! SQL Server 2008 is Still Here!
Help! SQL Server 2008 is Still Here!
 
An Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent OzarAn Introduction to GitHub for DBAs - Brent Ozar
An Introduction to GitHub for DBAs - Brent Ozar
 
SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?SQL Query Optimization: Why Is It So Hard to Get Right?
SQL Query Optimization: Why Is It So Hard to Get Right?
 
Headaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and DeadlockingHeadaches of Blocking, Locking, and Deadlocking
Headaches of Blocking, Locking, and Deadlocking
 
"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server Problems"But It Worked In Development!" - 3 Hard SQL Server Problems
"But It Worked In Development!" - 3 Hard SQL Server Problems
 
Columnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil AgarwalColumnstore Customer Stories 2016 by Sunil Agarwal
Columnstore Customer Stories 2016 by Sunil Agarwal
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Introduction to SQL Server Internals: How to Think Like the Engine

  • 1. Intro to Internals How to Think Like the SQL Engine Brent Ozar, Brent Ozar Unlimited
  • 2. MIT License Copyright © 2016 Brent Ozar. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  • 3. I know, I hate killing trees. But having these next 3 pages in your hand will help a lot as we talk through the demos. Print this 3-page PDF to follow along: http://u.BrentOzar.com/engine.pdf 3
  • 4. Brent Ozar Consultant, Brent Ozar Unlimited I make SQL Server faster and more reliable. I created sp_Blitz® and the SQL Server First Responder Kit, and I loves sharing knowledge at BrentOzar.com. I hold a bunch of certifications and awards including the rare Microsoft Certified Master. You don’t care about any of that though. Download the PDF: BrentOzar.com/go/enginepdf /brentozar @brento brentozar
  • 5. Agenda When you pass in a query, how does SQL Server build the results? Time to role play: Brent will be an end user sending in queries, and you will play the part of the SQL Server engine. Using simple spreadsheets as your tables, you will learn how SQL Server builds execution plans, uses indexes, performs joins, and considers statistics. This session is for DBAs and developers who are comfortable writing queries, but not so comfortable when it comes to explaining nonclustered indexes, lookups, sargability, fill factor, and corruption detection.
  • 6.
  • 7.
  • 8. Index OR Data Rows Slot Array 8KB Page header
  • 10.
  • 11.
  • 12.
  • 13. You: SQL Server. Me: end user.
  • 15. Your execution plan: 1. Shuffle through all of the pages, saying the Id of each record out loud.
  • 17. SET STATISTICS IO ON Logical reads: the number of 8K pages we read. (79,672 x 8KB = 637MB)
  • 19. Let’s add a filter. SELECT Id FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’
  • 20. Your execution plan: 1. Shuffle through all of the pages, saying the Id of each record out loud, if their LastAccessDate > ‘2014/07/01’.
  • 22.
  • 23. Lesson: Using a WHERE without a matching index means scanning all the data.
  • 24.
  • 25.
  • 26. Lesson: Estimated Subtree Cost guesses at CPU and IO work required for a query.
  • 27. Let’s add a sort. SELECT Id FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate
  • 28. 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.
  • 30.
  • 31. Cost is up ~4x We needed space to write down our results, so we got a memory grant Order By:
  • 32.
  • 33. 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. You can’t always get what you want.
  • 34. And if you run out of memory…
  • 35. Let’s get all the fields. SELECT * FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate
  • 36. 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.
  • 37. Lesson: SELECT * sucks. But let’s dig deeper.
  • 38. 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?
  • 40.
  • 41. SELECT ID SELECT * No order 66 66 ORDER BY 259 20,666
  • 42. Lesson: Sorting is expensive, and more fields makes it worse.
  • 43. Let’s run it a few times. SELECT * FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate; GO 5
  • 44. 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?
  • 45. Oracle can. (It better, since it costs $47,000 per core.)
  • 46. SQL Server reads & sorts 5 times.
  • 47. Lesson: SQL Server caches raw data pages, not output.
  • 48. Nonclustered indexes: copies. Stored in the order we want Include the fields we want CREATE INDEX IX_LastAccessDate_Id ON dbo.Users(LastAccessDate, Id)
  • 49. Let’s go simple again. SELECT Id FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate;
  • 50. Your execution plan 1. Grab IX_LastAccessDate and seek to 2014/07/01. 2. Read the Id’s out in order.
  • 52.
  • 53. SELECT ID SELECT * No order 66 66 ORDER BY 259 20,666 ORDER BY (with index) 10 6,354
  • 54.
  • 57. Yes, this is a “seek.”
  • 58. Don’t think scan = terrible.
  • 59. It covers the fields we need in this query. But if we change the query… That’s a covering index.
  • 60. Let’s add a couple of fields. SELECT Id, DisplayName, Age FROM dbo.Users WHERE LastAccessDate > ‘2014/07/01’ ORDER BY LastAccessDate;
  • 61. 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.
  • 62. The SQL Server equivalent
  • 63. For simplicity, I told you 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. That’s why SQL Server includes the key
  • 64. Key lookup is required when the index doesn’t have all the fields we need. Hover your mouse over the key lookup and look for the OUTPUT fields. Small? Frequently used? Add ‘em to the index. DO NOT ADD A NEW INDEX. Classic index tuning sign
  • 65. But to get that plan, I had to cheat.
  • 67. Lesson: Even with indexes, there’s a tipping point where scans work better.
  • 69. 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 Statistics help SQL Server:
  • 70.
  • 71. WHERE LastAccessDate > ‘2014/07/01’
  • 72. Add it up, add it up
  • 73.
  • 74. Automatic stats updates aren’t enough. Consider: • http://Ola.Hallengren.com • http://MinionWare.net/reindex Typical strategy: weekly statistics updates Updated statistics on an index invalidate query plans that involve that index • Affects your plan cache analysis • Can cause unpredictable query plan changes Keep statistics updated.
  • 75. How about on a single random date?
  • 76.
  • 77.
  • 78. Let’s write it differently.
  • 80. Why can’t I get just one row
  • 81. Lesson: This is called Cardinality Estimation, and it’s not just about keeping stats updated.
  • 82. The Cardinality Estimator has huge improvements. To turn ‘em on, just change your Compatibility Level. Fortunately, SQL 2014/2016 fixes this.
  • 83. And run the exact same query again
  • 86. Let’s add a join.
  • 87.
  • 88.
  • 89.
  • 90. Lesson: bad cardinality estimation is at the dark heart of many bad plans.
  • 91. Whew. That’s a lot of lessons.
  • 92. Clustered indexes hold all the fields* Nonclustered indexes are light-weight* copies of the table NC indexes reduce not just reads, but also CPU work SQL Server caches raw data pages, not query output Statistics drive seek vs scan, index choice, memory Statistics aren’t the only part: cardinality estimation matters Includes and seeks aren’t magically delicious What we learned
  • 93. Thank You Learn more from Brent Ozar help@brentozar.com or follow @BrentO

Notas del editor

  1. We’re using the StackOverflow.com database as an example. To get download it, go to http://BrentOzar.com/go/querystack. These screenshots are from the 2016/03 export, which is ~100GB. If you use a newer or older export, your numbers of pages may vary.
  2. This session focuses on the Users table Id – primary key, clustered index. It’s an identity, starts at 1 and goes into the millions. The white paper you’re holding in your hands – that’s the clustered index. It includes all of the fields on the table – sort of. Notice the About Me? It’s an NVARCHAR(MAX), and may not fit on a row. SQL Server may store that off-row, on other pages, if people get really wordy in their about-me field. We’re not going to touch on off-row data here, but I just want you to know there’s an overhead to that. Same thing with XML, JSON.
  3. For old-school tables, everything is stored in 8KB pages. These pages are the same whether they’re in memory or on disk. It’s the smallest unit of data SQL Server works with. (Things are different for Hekaton and columnstore indexes, but we’re focusing on old-school tables today.)
  4. 463x
  5. 463x
  6. Why can’t I get just one row