SlideShare a Scribd company logo
uy.vopen.tech
Query Tuning Techniques Every
SQL Server Programmer Should
Know
Rodrigo Crespi
Rodrigo Crespi
MCSE, MCSA, etc.
PostDegree in Data Base – UGF
PASS Chapter Leader – SQL Server RS
University Professor of Database Management
CrespiDB | Soluções em Plataforma de Dados
@SQLCrespi
rodrigocrespi
S Q L C r e s p i
sqlcrespi.com
SQLCrespi
First of All!
● Understand how a query works;
● Understand set theory;
● Most important try another thought.
SQL Server Architecture
P
r
o
t
o
c
o
l
o
s
Parser
Optimizer
SQL Mgr.
DB. Mgr.
Query
Executor
R
e
l
a
t
i
o
n
a
l
E
n
g
i
n
e
S
t
o
r
a
g
e
E
n
g
i
n
e
T-Services
Lock Mgr.
File Mgr.
Utilities
Access
Methods
SQLOS
SQLOS.dll
SQLLang.dll
PageLock Monitor
Resource Monitor
Lazy Writer
Scheduler Monitor
SQLmin.dll
Buffer Pool
Memory Mgr.
Scheduling
Sinc. Services
Lock Mgr.
I/O
SQLDK.dll
It’s a simple
representation
Relational Engine
Optimizer
Query
Executor
Cmd Parser
SNI
Protocol Layer
Storage Engine
Transactio
n Manager
Access
Methods
Buffer
Manager
Lock
Manager
Data Cache
Plan Cache
Data File
T-SQL
Select * from cliente
T
D
S
IF
Query Tree
O
L
E
D
B
IF
Buffer Pool
Query
Workspace
Query
Compile
Token Perm
XEvents,Metadados,
outros...
Relational Engine
Optimizer
Query
Executor
Cmd Parser
SNI
Protocol Layer
Storage Engine
Transactio
n Manager
Access
Methods
Buffer
Manager
Data File
T-SQL
Update cliente set nome = ‘Rodrigo’
T
D
S
IF
Query Tree
O
L
E
D
B
IF
Lazy Writer
CheckPoint
Lock Manager
Data Cache
Plan Cache
Buffer Pool
Query
Workspace
Query
Compile
Token Perm
Xevents,Metadados,
outros...
Dirty
Page
Physical Query Tree
• It is the way the optimizer calculates the most efficient path for executing the
command;
• More efficient or more optimized?
Zoom of Optimizer
Parsing / binding
Simplification
Start a joins set
Trivial Plan
Optimization phase
Search 0
Search 1
Search 2
Phase 0-Traditional: nested
Loops, with no parallelism
options.
Phase 1 – Fast: Uses a fast
subset of rules that
contains the most common
patterns.
Phase 2 – Complete: For
complex queries with
parallelism and indexed
views.
Before Optimization
Optimization
Tips
The best
pattern is the
one that every
team follows!
Pattern
Formatting T-SQL for Readability
● Comments, author, and brief audit trail;
● Be Consistent;
● The best formatting pattern is the one that is followed by the entire team.
How To Test a Query
● Clear caches;
● Try, Test and Compare;
● Set measurements;
● DMVs for check;
● Clone Database.
T-SQL Performance
• Set Statistics IO / Time;
• Compare the execution plans;
Predicates and Set Theory
● Say no to cursor;
● The Optimizer can’t pick the best execution plan if the
Stored Procedure is broken up into many parts;
● Built-In functions that can affect performance;
● Like;
● And | Or | In;
● Union and union all;
● IsNull();
Implicit Conversions
● The optimizer chooses the data type based on a predefined list;
○ https://docs.microsoft.com/en-us/sql/t-sql/data-types/data-
type-precedence-transact-
sql?redirectedfrom=MSDN&view=sql-server-ver15
● Data Types matter;
● You may not get what you expect;
● Implicit conversions can be costly.
Lock and NoLock
Lock is required in SQL
Databases. This is a true!
HOWEVER, if you use
hint nolock pay attention
if you reading a dirty page!
3 query tuning techniques every sql server programmer should know
SPONSORS
¡Gracias!
@SQLCrespi

More Related Content

PDF
Islamabad PUG - 7th meetup - performance tuning
PDF
Growing up new PostgreSQL developers (pgcon.org 2018)
PDF
JChem Microservices
ODP
Spark Structured Streaming
PPTX
Moving advanced analytics to your sql server databases
PDF
Islamabad PUG - 7th Meetup - performance tuning
PDF
kranonit S06E01 Игорь Цинько: High load
PPT
Oracle Sql Tuning
Islamabad PUG - 7th meetup - performance tuning
Growing up new PostgreSQL developers (pgcon.org 2018)
JChem Microservices
Spark Structured Streaming
Moving advanced analytics to your sql server databases
Islamabad PUG - 7th Meetup - performance tuning
kranonit S06E01 Игорь Цинько: High load
Oracle Sql Tuning

Similar to 3 query tuning techniques every sql server programmer should know (20)

PDF
Introduction to Web Development with Ruby on Rails
PDF
Key to a successful Exadata POC
PDF
Must Know Postgres Extension for DBA and Developer during Migration
PPTX
OutSystems Tips and Tricks
PDF
Evolution of DBA in the Cloud Era
PPTX
Cqrs and Event Sourcing Intro For Developers
PDF
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
PPTX
Database Fundamental Concepts- Series 1 - Performance Analysis
PPTX
Before you optimize: Understanding Execution Plans
PPTX
Improving The Quality of Existing Software
PDF
Migrating Oracle database to PostgreSQL
PPTX
Optimising Queries - Series 1 Query Optimiser Architecture
PDF
31063115_1679409488310Developer_Tuning_Tips_-_UTOUG_Mar_2023.pdf
PDF
MongoDB Online Training.pdf
PDF
Plpgsql russia-pgconf
PPTX
The Plan Cache Whisperer - Performance Tuning SQL Server
PPTX
שבוע אורקל 2016
PDF
PostgreSQL for Oracle Developers and DBA's
PDF
Selena Deckelmann - Sane Schema Management with Alembic and SQLAlchemy @ Pos...
PDF
The Diabolical Developers Guide to Performance Tuning
Introduction to Web Development with Ruby on Rails
Key to a successful Exadata POC
Must Know Postgres Extension for DBA and Developer during Migration
OutSystems Tips and Tricks
Evolution of DBA in the Cloud Era
Cqrs and Event Sourcing Intro For Developers
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Database Fundamental Concepts- Series 1 - Performance Analysis
Before you optimize: Understanding Execution Plans
Improving The Quality of Existing Software
Migrating Oracle database to PostgreSQL
Optimising Queries - Series 1 Query Optimiser Architecture
31063115_1679409488310Developer_Tuning_Tips_-_UTOUG_Mar_2023.pdf
MongoDB Online Training.pdf
Plpgsql russia-pgconf
The Plan Cache Whisperer - Performance Tuning SQL Server
שבוע אורקל 2016
PostgreSQL for Oracle Developers and DBA's
Selena Deckelmann - Sane Schema Management with Alembic and SQLAlchemy @ Pos...
The Diabolical Developers Guide to Performance Tuning
Ad

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Getting Started with Data Integration: FME Form 101
PDF
Machine learning based COVID-19 study performance prediction
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Approach and Philosophy of On baking technology
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Big Data Technologies - Introduction.pptx
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Getting Started with Data Integration: FME Form 101
Machine learning based COVID-19 study performance prediction
Mobile App Security Testing_ A Comprehensive Guide.pdf
Machine Learning_overview_presentation.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation_ Review paper, used for researhc scholars
Network Security Unit 5.pdf for BCA BBA.
gpt5_lecture_notes_comprehensive_20250812015547.pdf
MYSQL Presentation for SQL database connectivity
Approach and Philosophy of On baking technology
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Dropbox Q2 2025 Financial Results & Investor Presentation
MIND Revenue Release Quarter 2 2025 Press Release
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Ad

3 query tuning techniques every sql server programmer should know

  • 2. Query Tuning Techniques Every SQL Server Programmer Should Know Rodrigo Crespi
  • 3. Rodrigo Crespi MCSE, MCSA, etc. PostDegree in Data Base – UGF PASS Chapter Leader – SQL Server RS University Professor of Database Management CrespiDB | Soluções em Plataforma de Dados @SQLCrespi rodrigocrespi S Q L C r e s p i sqlcrespi.com SQLCrespi
  • 4. First of All! ● Understand how a query works; ● Understand set theory; ● Most important try another thought.
  • 5. SQL Server Architecture P r o t o c o l o s Parser Optimizer SQL Mgr. DB. Mgr. Query Executor R e l a t i o n a l E n g i n e S t o r a g e E n g i n e T-Services Lock Mgr. File Mgr. Utilities Access Methods SQLOS SQLOS.dll SQLLang.dll PageLock Monitor Resource Monitor Lazy Writer Scheduler Monitor SQLmin.dll Buffer Pool Memory Mgr. Scheduling Sinc. Services Lock Mgr. I/O SQLDK.dll It’s a simple representation
  • 6. Relational Engine Optimizer Query Executor Cmd Parser SNI Protocol Layer Storage Engine Transactio n Manager Access Methods Buffer Manager Lock Manager Data Cache Plan Cache Data File T-SQL Select * from cliente T D S IF Query Tree O L E D B IF Buffer Pool Query Workspace Query Compile Token Perm XEvents,Metadados, outros...
  • 7. Relational Engine Optimizer Query Executor Cmd Parser SNI Protocol Layer Storage Engine Transactio n Manager Access Methods Buffer Manager Data File T-SQL Update cliente set nome = ‘Rodrigo’ T D S IF Query Tree O L E D B IF Lazy Writer CheckPoint Lock Manager Data Cache Plan Cache Buffer Pool Query Workspace Query Compile Token Perm Xevents,Metadados, outros... Dirty Page
  • 8. Physical Query Tree • It is the way the optimizer calculates the most efficient path for executing the command; • More efficient or more optimized?
  • 9. Zoom of Optimizer Parsing / binding Simplification Start a joins set Trivial Plan Optimization phase Search 0 Search 1 Search 2 Phase 0-Traditional: nested Loops, with no parallelism options. Phase 1 – Fast: Uses a fast subset of rules that contains the most common patterns. Phase 2 – Complete: For complex queries with parallelism and indexed views. Before Optimization Optimization
  • 10. Tips
  • 11. The best pattern is the one that every team follows! Pattern
  • 12. Formatting T-SQL for Readability ● Comments, author, and brief audit trail; ● Be Consistent; ● The best formatting pattern is the one that is followed by the entire team.
  • 13. How To Test a Query ● Clear caches; ● Try, Test and Compare; ● Set measurements; ● DMVs for check; ● Clone Database.
  • 14. T-SQL Performance • Set Statistics IO / Time; • Compare the execution plans;
  • 15. Predicates and Set Theory ● Say no to cursor; ● The Optimizer can’t pick the best execution plan if the Stored Procedure is broken up into many parts; ● Built-In functions that can affect performance; ● Like; ● And | Or | In; ● Union and union all; ● IsNull();
  • 16. Implicit Conversions ● The optimizer chooses the data type based on a predefined list; ○ https://docs.microsoft.com/en-us/sql/t-sql/data-types/data- type-precedence-transact- sql?redirectedfrom=MSDN&view=sql-server-ver15 ● Data Types matter; ● You may not get what you expect; ● Implicit conversions can be costly.
  • 17. Lock and NoLock Lock is required in SQL Databases. This is a true! HOWEVER, if you use hint nolock pay attention if you reading a dirty page!