SlideShare a Scribd company logo
SQL Query Performance Analysis
Topics To Cover
• Query Optimizer

• Addhoc queries

• Execution Plan

• Statistics Analysis
Query Optimizer
The query optimizer in SQL Server is cost-based. It includes:

1. Cost for using different resources (CPU and IO)
2. Total execution time

It determines the cost by using:

• Cardinality: The total number of rows processed at each level
  of a query plan with the help of histograms , predicates and
  constraint

• Cost model of the algorithm: To perform various operations
  like sorting, searching, comparisons etc.
Addhoc queries
Any non-Parameterized quires are called addhoc queries. For
example :

SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 100

In sql server if we execute a sql query it goes through two steps
just like any other programming languages:

• 1. Compilation
• 2. Execution
Properties of addhoc query
• Case sensitive
• Space sensitive
• Parameter sensitive

Sql severs treats two same sql query but of different parameters
as different sql statements. For example:

• SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 1
• SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 2
Effect of faulty C# code
• Sql server has took extra n * (Compilation time) ms to display
  records

• Extra time to insert records in cached plans.

• Sql server has to frequently fire a job to delete the cached
  plan since it will reach the max limit very soon.

• It will not only decrease the performance of this sql query but
  all sql queries of other application since this faulty code will
  force to delete cached query plans of other sql statement.
Prepared queries
Example:

(@Msgid int)SELECT MsgID, Severity FROM SqlMessage WHERE
  MsgID = @Msgid

• It is not case, space and parameter sensitive and it is our goal.

Stored procedure :

• It is precompiled sql queries which follow a common
  execution plan.
Execution Plan
• What is an index in sql server?

  Index is a way to organize data in a table to make some
  operations like searching, sorting, grouping etc faster. So, in
  other word we need indexing when sql query has:

• WHERE clause (That is searching)
• ORDER BY clause (That is sorting)
• GROUP BY clause (This is grouping) etc.
Table scan:
SELECT * FROM Student WHERE RollNo = 111


Time complexity of table scan is : O(n)
RollNo          Name              Country     Age
101             Greg              UK          23
102             Sachin            India       21
103             Akaram            Pakistan    22
107             Miyabi            China       18
108             Marry             Russia      27
109             Scott             USA         31
110             Benazir           Banglades   17
111             Miyabi            Japan       24
112             Rahul             India       27
113             Nicolus           France      19
Clustered index
• When we create a clustered index on any
  table physical organization of table is changed.

• Now data of table is stored as binary search
  tree(B tree).
Sql query performance analysis
Types of scanning
• Table scan: It is very slow can and it is used only if table has
  not any clustered index.

• Index scan: It is also slow scan. It is used when table has
  clustered index and either in WHERE clause non-key columns
  are present or query has not been covered (will discuss later)
  or both.

• Index Seek: It is very fast. Our goal is to achieve this.
Terms of execution plan
• Predicate: It is condition in WHERE clause which is either non-
  key column or column which has not been covered.

• Object: It is name of source from where it getting the data. It
  can be name of table, Clustered index or non-clustered index

• Output list: It is name of the columns which is getting from
  object.

• Seek Predicate: It is condition in WHERE clause which is either
  key column or fully covered.
Non-clustered index
• It is logical organization of data of table. A non-clustered index
  can be of two types.

1. Heap
2. Based on clustered index.

• If table has clustered index then leaf node of non-clustered
  index keeps the key columns of clustered index.

• If the table has not any clustered index then leaf node of non-
  clustered index keeps RID which unique of each row of table.
Based on clustered Index
Based on heap
Covering of queries
• We can specify maximum 16 column names.

•   Sum of size of the columns cannot be more than 900 bytes.

• All columns must belong to same table.

• Data     type    of    columns      cannot     be     ntext,  text,
  varchar (max), nvarchar (max), varbinary (max), xml, or image

• It cannot be non-deterministic computed column.
Statistics Analysis
• The query optimizer uses statistics to create query plans that
  improve query performance

• A correct statistics will lead to high-quality query plan.

• Auto create and updates applies strictly to single-column
  statistics.

• The query optimizer determines when statistics might be out-
  of-date by counting the number of data modifications since
  the last statistics update and comparing the number of
  modifications to a threshold.
To improve cardinality
• If possible, simplify expressions with constants in them.

• If there is cross relation between column use computed
  column.

• Rewriting the query to use a parameter instead of a local
  variable.

• Avoid changing the parameter value within the stored
  procedure before using it in the query.
Goal
• Should we use sub query or inner join?
• Should we use temp table or table variable?

Other tools:

•   Sql query profiler
•   Database Tuning Advisor
•   Resource Governor
THANK YOU

More Related Content

What's hot (20)

PPTX
Do IT with SQL
Nur Hidayat
 
PPTX
How nebula graph index works
Nebula Graph
 
PPTX
Indexing the MySQL Index: Key to performance tuning
OSSCube
 
PDF
8 query processing and optimization
Kumar
 
PPTX
R- Introduction
Venkata Reddy Konasani
 
PPT
Query processing-and-optimization
WBUTTUTORIALS
 
PDF
Elasticsearch 101 - Cluster setup and tuning
Petar Djekic
 
PPTX
Query evaluation and optimization
lavanya marichamy
 
PPTX
New T-SQL Features in SQL Server 2012
Richie Rump
 
PPTX
Step By Step Guide to Learn R
Venkata Reddy Konasani
 
PDF
InfiniFlux Minmax Cache
InfiniFlux
 
PPTX
Executing Queries on a Sharded Database
Neha Narula
 
PDF
B+Tree Indexes and InnoDB
Ovais Tariq
 
PPT
Chapter15
gourab87
 
PPT
The No SQL Principles and Basic Application Of Casandra Model
Rishikese MR
 
PPT
Synapseindia dot net development chapter 8 asp dot net
Synapseindiappsdevelopment
 
PPT
Myth busters - performance tuning 102 2008
paulguerin
 
PDF
Advanced data structures vol. 1
Christalin Nelson
 
PPTX
Sharding Overview
MongoDB
 
Do IT with SQL
Nur Hidayat
 
How nebula graph index works
Nebula Graph
 
Indexing the MySQL Index: Key to performance tuning
OSSCube
 
8 query processing and optimization
Kumar
 
R- Introduction
Venkata Reddy Konasani
 
Query processing-and-optimization
WBUTTUTORIALS
 
Elasticsearch 101 - Cluster setup and tuning
Petar Djekic
 
Query evaluation and optimization
lavanya marichamy
 
New T-SQL Features in SQL Server 2012
Richie Rump
 
Step By Step Guide to Learn R
Venkata Reddy Konasani
 
InfiniFlux Minmax Cache
InfiniFlux
 
Executing Queries on a Sharded Database
Neha Narula
 
B+Tree Indexes and InnoDB
Ovais Tariq
 
Chapter15
gourab87
 
The No SQL Principles and Basic Application Of Casandra Model
Rishikese MR
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindiappsdevelopment
 
Myth busters - performance tuning 102 2008
paulguerin
 
Advanced data structures vol. 1
Christalin Nelson
 
Sharding Overview
MongoDB
 

Viewers also liked (8)

PDF
E government 2012 Colombia
Comercio Electronico
 
PDF
Estudio benchmark publicidad digital mayor rendimiento por media mind
Comercio Electronico
 
PPTX
Query parameterization
Riteshkiit
 
PPT
You are all dead to me
zedgrangerson
 
PDF
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
Comercio Electronico
 
PPTX
Sql server 2
Riteshkiit
 
PPTX
Sql server introduction fundamental
Riteshkiit
 
PDF
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
Comercio Electronico
 
E government 2012 Colombia
Comercio Electronico
 
Estudio benchmark publicidad digital mayor rendimiento por media mind
Comercio Electronico
 
Query parameterization
Riteshkiit
 
You are all dead to me
zedgrangerson
 
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
Comercio Electronico
 
Sql server 2
Riteshkiit
 
Sql server introduction fundamental
Riteshkiit
 
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
Comercio Electronico
 
Ad

Similar to Sql query performance analysis (20)

PPTX
Index_2
Riteshkiit
 
PDF
Sql Server Query Parameterization
Mindfire Solutions
 
PDF
Statistics and Indexes Internals
Antonios Chatzipavlis
 
PPTX
Index the obvious and not so obvious
Harry Zheng
 
PDF
Managing Statistics for Optimal Query Performance
Karen Morton
 
PPTX
Statistics
Riteshkiit
 
PPTX
SQL Server 2012 Best Practices
Microsoft TechNet - Belgium and Luxembourg
 
PPTX
Sql and PL/SQL Best Practices I
Carlos Oliveira
 
PDF
Microsoft SQL Server Filtered Indexes & Sparse Columns Feb 2011
Mark Ginnebaugh
 
PPTX
Query Optimization in SQL Server
Rajesh Gunasundaram
 
PDF
Practical SQL query monitoring and optimization
Ivo Andreev
 
PPTX
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
Fwdays
 
PPTX
Geek Sync | Understand Indexes to Write Better Queries
IDERA Software
 
PPTX
Database Performance
Boris Hristov
 
PPTX
DB
Samchu Li
 
PPTX
dotnetMALAGA - Sql query tuning guidelines
Javier García Magna
 
PDF
Brad McGehee Intepreting Execution Plans Mar09
Mark Ginnebaugh
 
PDF
Brad McGehee Intepreting Execution Plans Mar09
guest9d79e073
 
PDF
Indexes overview
aioughydchapter
 
PPT
Indexing Strategies
jlaspada
 
Index_2
Riteshkiit
 
Sql Server Query Parameterization
Mindfire Solutions
 
Statistics and Indexes Internals
Antonios Chatzipavlis
 
Index the obvious and not so obvious
Harry Zheng
 
Managing Statistics for Optimal Query Performance
Karen Morton
 
Statistics
Riteshkiit
 
SQL Server 2012 Best Practices
Microsoft TechNet - Belgium and Luxembourg
 
Sql and PL/SQL Best Practices I
Carlos Oliveira
 
Microsoft SQL Server Filtered Indexes & Sparse Columns Feb 2011
Mark Ginnebaugh
 
Query Optimization in SQL Server
Rajesh Gunasundaram
 
Practical SQL query monitoring and optimization
Ivo Andreev
 
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
Fwdays
 
Geek Sync | Understand Indexes to Write Better Queries
IDERA Software
 
Database Performance
Boris Hristov
 
dotnetMALAGA - Sql query tuning guidelines
Javier García Magna
 
Brad McGehee Intepreting Execution Plans Mar09
Mark Ginnebaugh
 
Brad McGehee Intepreting Execution Plans Mar09
guest9d79e073
 
Indexes overview
aioughydchapter
 
Indexing Strategies
jlaspada
 
Ad

More from Riteshkiit (7)

PPTX
Backup and restore
Riteshkiit
 
PPTX
Database index
Riteshkiit
 
PPTX
Order by and join
Riteshkiit
 
PPTX
Database design
Riteshkiit
 
PPTX
Addhoc query
Riteshkiit
 
PPTX
Sql server JOIN
Riteshkiit
 
PPTX
Topics
Riteshkiit
 
Backup and restore
Riteshkiit
 
Database index
Riteshkiit
 
Order by and join
Riteshkiit
 
Database design
Riteshkiit
 
Addhoc query
Riteshkiit
 
Sql server JOIN
Riteshkiit
 
Topics
Riteshkiit
 

Recently uploaded (20)

DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
Designing Production-Ready AI Agents
Kunal Rai
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
July Patch Tuesday
Ivanti
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Designing Production-Ready AI Agents
Kunal Rai
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
July Patch Tuesday
Ivanti
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 

Sql query performance analysis

  • 2. Topics To Cover • Query Optimizer • Addhoc queries • Execution Plan • Statistics Analysis
  • 3. Query Optimizer The query optimizer in SQL Server is cost-based. It includes: 1. Cost for using different resources (CPU and IO) 2. Total execution time It determines the cost by using: • Cardinality: The total number of rows processed at each level of a query plan with the help of histograms , predicates and constraint • Cost model of the algorithm: To perform various operations like sorting, searching, comparisons etc.
  • 4. Addhoc queries Any non-Parameterized quires are called addhoc queries. For example : SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 100 In sql server if we execute a sql query it goes through two steps just like any other programming languages: • 1. Compilation • 2. Execution
  • 5. Properties of addhoc query • Case sensitive • Space sensitive • Parameter sensitive Sql severs treats two same sql query but of different parameters as different sql statements. For example: • SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 1 • SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 2
  • 6. Effect of faulty C# code • Sql server has took extra n * (Compilation time) ms to display records • Extra time to insert records in cached plans. • Sql server has to frequently fire a job to delete the cached plan since it will reach the max limit very soon. • It will not only decrease the performance of this sql query but all sql queries of other application since this faulty code will force to delete cached query plans of other sql statement.
  • 7. Prepared queries Example: (@Msgid int)SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = @Msgid • It is not case, space and parameter sensitive and it is our goal. Stored procedure : • It is precompiled sql queries which follow a common execution plan.
  • 8. Execution Plan • What is an index in sql server? Index is a way to organize data in a table to make some operations like searching, sorting, grouping etc faster. So, in other word we need indexing when sql query has: • WHERE clause (That is searching) • ORDER BY clause (That is sorting) • GROUP BY clause (This is grouping) etc.
  • 9. Table scan: SELECT * FROM Student WHERE RollNo = 111 Time complexity of table scan is : O(n) RollNo Name Country Age 101 Greg UK 23 102 Sachin India 21 103 Akaram Pakistan 22 107 Miyabi China 18 108 Marry Russia 27 109 Scott USA 31 110 Benazir Banglades 17 111 Miyabi Japan 24 112 Rahul India 27 113 Nicolus France 19
  • 10. Clustered index • When we create a clustered index on any table physical organization of table is changed. • Now data of table is stored as binary search tree(B tree).
  • 12. Types of scanning • Table scan: It is very slow can and it is used only if table has not any clustered index. • Index scan: It is also slow scan. It is used when table has clustered index and either in WHERE clause non-key columns are present or query has not been covered (will discuss later) or both. • Index Seek: It is very fast. Our goal is to achieve this.
  • 13. Terms of execution plan • Predicate: It is condition in WHERE clause which is either non- key column or column which has not been covered. • Object: It is name of source from where it getting the data. It can be name of table, Clustered index or non-clustered index • Output list: It is name of the columns which is getting from object. • Seek Predicate: It is condition in WHERE clause which is either key column or fully covered.
  • 14. Non-clustered index • It is logical organization of data of table. A non-clustered index can be of two types. 1. Heap 2. Based on clustered index. • If table has clustered index then leaf node of non-clustered index keeps the key columns of clustered index. • If the table has not any clustered index then leaf node of non- clustered index keeps RID which unique of each row of table.
  • 17. Covering of queries • We can specify maximum 16 column names. • Sum of size of the columns cannot be more than 900 bytes. • All columns must belong to same table. • Data type of columns cannot be ntext, text, varchar (max), nvarchar (max), varbinary (max), xml, or image • It cannot be non-deterministic computed column.
  • 18. Statistics Analysis • The query optimizer uses statistics to create query plans that improve query performance • A correct statistics will lead to high-quality query plan. • Auto create and updates applies strictly to single-column statistics. • The query optimizer determines when statistics might be out- of-date by counting the number of data modifications since the last statistics update and comparing the number of modifications to a threshold.
  • 19. To improve cardinality • If possible, simplify expressions with constants in them. • If there is cross relation between column use computed column. • Rewriting the query to use a parameter instead of a local variable. • Avoid changing the parameter value within the stored procedure before using it in the query.
  • 20. Goal • Should we use sub query or inner join? • Should we use temp table or table variable? Other tools: • Sql query profiler • Database Tuning Advisor • Resource Governor