SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

Course 102: Lecture 22: Package Management
Course 102: Lecture 22: Package Management Course 102: Lecture 22: Package Management
Course 102: Lecture 22: Package Management Ahmed El-Arabawy
 
VLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-StoresVLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-StoresDaniel Abadi
 
InnoDB Internal
InnoDB InternalInnoDB Internal
InnoDB Internalmysqlops
 
What’s New in Oracle Database 19c - Part 1
What’s New in Oracle Database 19c - Part 1What’s New in Oracle Database 19c - Part 1
What’s New in Oracle Database 19c - Part 1Satishbabu Gunukula
 
Why oracle data guard new features in oracle 18c, 19c
Why oracle data guard new features in oracle 18c, 19cWhy oracle data guard new features in oracle 18c, 19c
Why oracle data guard new features in oracle 18c, 19cSatishbabu Gunukula
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpen Gurukul
 
Oracle RDBMS architecture
Oracle RDBMS architectureOracle RDBMS architecture
Oracle RDBMS architectureMartin Berger
 
MySQL Atchitecture and Concepts
MySQL Atchitecture and ConceptsMySQL Atchitecture and Concepts
MySQL Atchitecture and ConceptsTuyen Vuong
 
Oracle Architecture
Oracle ArchitectureOracle Architecture
Oracle ArchitectureNeeraj Singh
 
Nabil Nawaz Oracle Oracle 12c Data Guard Deep Dive Presentation
Nabil Nawaz Oracle Oracle 12c Data Guard Deep Dive PresentationNabil Nawaz Oracle Oracle 12c Data Guard Deep Dive Presentation
Nabil Nawaz Oracle Oracle 12c Data Guard Deep Dive PresentationNabil Nawaz
 
Architecture of exadata database machine – Part II
Architecture of exadata database machine – Part IIArchitecture of exadata database machine – Part II
Architecture of exadata database machine – Part IIParesh Nayak,OCP®,Prince2®
 
Step by Step Restore rman to different host
Step by Step Restore rman to different hostStep by Step Restore rman to different host
Step by Step Restore rman to different hostOsama Mustafa
 
Oracle Database performance tuning using oratop
Oracle Database performance tuning using oratopOracle Database performance tuning using oratop
Oracle Database performance tuning using oratopSandesh Rao
 
Rapid Upgrades with Pg_Upgrade
Rapid Upgrades with Pg_UpgradeRapid Upgrades with Pg_Upgrade
Rapid Upgrades with Pg_UpgradeEDB
 
Explaining Explain
Explaining ExplainExplaining Explain
Explaining ExplainRobert Treat
 
PostGreSQL Performance Tuning
PostGreSQL Performance TuningPostGreSQL Performance Tuning
PostGreSQL Performance TuningMaven Logix
 

What's hot (20)

Course 102: Lecture 22: Package Management
Course 102: Lecture 22: Package Management Course 102: Lecture 22: Package Management
Course 102: Lecture 22: Package Management
 
VLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-StoresVLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-Stores
 
InnoDB Internal
InnoDB InternalInnoDB Internal
InnoDB Internal
 
What’s New in Oracle Database 19c - Part 1
What’s New in Oracle Database 19c - Part 1What’s New in Oracle Database 19c - Part 1
What’s New in Oracle Database 19c - Part 1
 
MySQL Backup & Recovery
MySQL Backup & RecoveryMySQL Backup & Recovery
MySQL Backup & Recovery
 
Backup And Recovery
Backup And RecoveryBackup And Recovery
Backup And Recovery
 
Why oracle data guard new features in oracle 18c, 19c
Why oracle data guard new features in oracle 18c, 19cWhy oracle data guard new features in oracle 18c, 19c
Why oracle data guard new features in oracle 18c, 19c
 
OpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQLOpenGurukul : Database : PostgreSQL
OpenGurukul : Database : PostgreSQL
 
Oracle RDBMS architecture
Oracle RDBMS architectureOracle RDBMS architecture
Oracle RDBMS architecture
 
MySQL Atchitecture and Concepts
MySQL Atchitecture and ConceptsMySQL Atchitecture and Concepts
MySQL Atchitecture and Concepts
 
Oracle Architecture
Oracle ArchitectureOracle Architecture
Oracle Architecture
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Nabil Nawaz Oracle Oracle 12c Data Guard Deep Dive Presentation
Nabil Nawaz Oracle Oracle 12c Data Guard Deep Dive PresentationNabil Nawaz Oracle Oracle 12c Data Guard Deep Dive Presentation
Nabil Nawaz Oracle Oracle 12c Data Guard Deep Dive Presentation
 
Architecture of exadata database machine – Part II
Architecture of exadata database machine – Part IIArchitecture of exadata database machine – Part II
Architecture of exadata database machine – Part II
 
Oracle Complete Interview Questions
Oracle Complete Interview QuestionsOracle Complete Interview Questions
Oracle Complete Interview Questions
 
Step by Step Restore rman to different host
Step by Step Restore rman to different hostStep by Step Restore rman to different host
Step by Step Restore rman to different host
 
Oracle Database performance tuning using oratop
Oracle Database performance tuning using oratopOracle Database performance tuning using oratop
Oracle Database performance tuning using oratop
 
Rapid Upgrades with Pg_Upgrade
Rapid Upgrades with Pg_UpgradeRapid Upgrades with Pg_Upgrade
Rapid Upgrades with Pg_Upgrade
 
Explaining Explain
Explaining ExplainExplaining Explain
Explaining Explain
 
PostGreSQL Performance Tuning
PostGreSQL Performance TuningPostGreSQL Performance Tuning
PostGreSQL Performance Tuning
 

Viewers also liked

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
 
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
 
JCI Syria 2017 Plan of Action #YOUthCanDO
JCI Syria 2017 Plan of Action #YOUthCanDOJCI Syria 2017 Plan of Action #YOUthCanDO
JCI Syria 2017 Plan of Action #YOUthCanDOMuhamad SHABAREK
 

Viewers also liked (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
 
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
 
JCI Syria 2017 Plan of Action #YOUthCanDO
JCI Syria 2017 Plan of Action #YOUthCanDOJCI Syria 2017 Plan of Action #YOUthCanDO
JCI Syria 2017 Plan of Action #YOUthCanDO
 

Similar to 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 to 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
 

More from 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
 

More from 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
 

Recently uploaded

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Recently uploaded (20)

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

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

Editor's Notes

  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