SlideShare a Scribd company logo
1 of 21
SQL Query Performance Analysis
INDEX
• 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 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 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 for
  particular key. We need indexing when cached query plan
  has:

• WHERE , HAVING, ON clause (That is searching)
• ORDER BY clause (That is sorting)
• GROUP BY clause (This is grouping) etc.
Table scan and Index 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 in B- Tree.

• Leaf node of clustered index always keep actual data.

• If we create table with primary key, sql server automatically
  creates clustered index on that table .

• If clustered index has more than one partition then each
  partition has a B-tree.
Index seek
Time complexity of index seek is: O(log n)
Types of scanning
• Table scan: It is very slow scanning process and it is used only
  if table has not any clustered index.

• Index scan: It is also slow scanning process. 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.

• If a table has only five records which scanning will you follow?
Terms of execution plan
• Predicate: It is condition in WHERE clause which is either non-
  key column or column which has not been covered.

• Seek Predicate: It is condition in WHERE clause which is either
  key column or fully covered.

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

• Output list: It is name of the columns which are getting from
  the object.
Non-clustered index
• It is logical organization of data of table. A non-clustered index
  can be of two types.

1. Based on 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.

• In heap leaf node of non-clustered index keeps RID.
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 or updated 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

Row level security in enterprise applications
Row level security in enterprise applicationsRow level security in enterprise applications
Row level security in enterprise applicationsAlexander Tokarev
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL ServerRajesh Gunasundaram
 
Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...
Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...
Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...Lucidworks
 
Executing Queries on a Sharded Database
Executing Queries on a Sharded DatabaseExecuting Queries on a Sharded Database
Executing Queries on a Sharded DatabaseNeha Narula
 
How to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftHow to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftAWS Germany
 
Elastic Migration 2.x to 6.x By Pankaj Gajjar
Elastic Migration 2.x to 6.x By Pankaj GajjarElastic Migration 2.x to 6.x By Pankaj Gajjar
Elastic Migration 2.x to 6.x By Pankaj GajjarPankaj Gajjar
 
Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"Lviv Startup Club
 
Elk presentation1#3
Elk presentation1#3Elk presentation1#3
Elk presentation1#3uzzal basak
 
Indexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuningIndexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuningOSSCube
 
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Michael Rys
 
Incorta spark integration
Incorta spark integrationIncorta spark integration
Incorta spark integrationDylan Wan
 
Improved Search With Lucene 4.0 - NOVA Lucene/Solr Meetup
Improved Search With Lucene 4.0 - NOVA Lucene/Solr MeetupImproved Search With Lucene 4.0 - NOVA Lucene/Solr Meetup
Improved Search With Lucene 4.0 - NOVA Lucene/Solr Meetuprcmuir
 
Three steps to untangle data traffic jams
Three steps to untangle data traffic jamsThree steps to untangle data traffic jams
Three steps to untangle data traffic jamsBol.com Techlab
 
Inmemory BI based on opensource stack
Inmemory BI based on opensource stackInmemory BI based on opensource stack
Inmemory BI based on opensource stackAlexander Tokarev
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning Arno Huetter
 
PandasUDFs: One Weird Trick to Scaled Ensembles
PandasUDFs: One Weird Trick to Scaled EnsemblesPandasUDFs: One Weird Trick to Scaled Ensembles
PandasUDFs: One Weird Trick to Scaled EnsemblesDatabricks
 
SQL on Big Data using Optiq
SQL on Big Data using OptiqSQL on Big Data using Optiq
SQL on Big Data using OptiqJulian Hyde
 

What's hot (20)

Row level security in enterprise applications
Row level security in enterprise applicationsRow level security in enterprise applications
Row level security in enterprise applications
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL Server
 
Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...
Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...
Efficient Scalable Search in a Multi-Tenant Environment: Presented by Harry H...
 
Unit Testing SQL Server
Unit Testing SQL ServerUnit Testing SQL Server
Unit Testing SQL Server
 
Executing Queries on a Sharded Database
Executing Queries on a Sharded DatabaseExecuting Queries on a Sharded Database
Executing Queries on a Sharded Database
 
How to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftHow to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon Redshift
 
Elastic Migration 2.x to 6.x By Pankaj Gajjar
Elastic Migration 2.x to 6.x By Pankaj GajjarElastic Migration 2.x to 6.x By Pankaj Gajjar
Elastic Migration 2.x to 6.x By Pankaj Gajjar
 
Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"Maryna Popova "Deep dive AWS Redshift"
Maryna Popova "Deep dive AWS Redshift"
 
Elk presentation1#3
Elk presentation1#3Elk presentation1#3
Elk presentation1#3
 
Indexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuningIndexing the MySQL Index: Key to performance tuning
Indexing the MySQL Index: Key to performance tuning
 
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
Introduction to Azure Data Lake and U-SQL for SQL users (SQL Saturday 635)
 
Cost-based Query Optimization
Cost-based Query Optimization Cost-based Query Optimization
Cost-based Query Optimization
 
Incorta spark integration
Incorta spark integrationIncorta spark integration
Incorta spark integration
 
Improved Search With Lucene 4.0 - NOVA Lucene/Solr Meetup
Improved Search With Lucene 4.0 - NOVA Lucene/Solr MeetupImproved Search With Lucene 4.0 - NOVA Lucene/Solr Meetup
Improved Search With Lucene 4.0 - NOVA Lucene/Solr Meetup
 
Three steps to untangle data traffic jams
Three steps to untangle data traffic jamsThree steps to untangle data traffic jams
Three steps to untangle data traffic jams
 
Inmemory BI based on opensource stack
Inmemory BI based on opensource stackInmemory BI based on opensource stack
Inmemory BI based on opensource stack
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
 
PandasUDFs: One Weird Trick to Scaled Ensembles
PandasUDFs: One Weird Trick to Scaled EnsemblesPandasUDFs: One Weird Trick to Scaled Ensembles
PandasUDFs: One Weird Trick to Scaled Ensembles
 
Search at Twitter
Search at TwitterSearch at Twitter
Search at Twitter
 
SQL on Big Data using Optiq
SQL on Big Data using OptiqSQL on Big Data using Optiq
SQL on Big Data using Optiq
 

Similar to Sql query performance analysis

Query parameterization
Query parameterizationQuery parameterization
Query parameterizationRiteshkiit
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server DatabasesColdFusionConference
 
POLARDB for MySQL - Parallel Query
POLARDB for MySQL - Parallel QueryPOLARDB for MySQL - Parallel Query
POLARDB for MySQL - Parallel Queryoysteing
 
SAG_Indexing and Query Optimization
SAG_Indexing and Query OptimizationSAG_Indexing and Query Optimization
SAG_Indexing and Query OptimizationVaibhav Jain
 
SQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET DeveloperSQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET DeveloperPolish SQL Server User Group
 
AWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationAWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationVolodymyr Rovetskiy
 
How nebula graph index works
How nebula graph index worksHow nebula graph index works
How nebula graph index worksNebula Graph
 
AWS June 2016 Webinar Series - Amazon Redshift or Big Data Analytics
AWS June 2016 Webinar Series - Amazon Redshift or Big Data AnalyticsAWS June 2016 Webinar Series - Amazon Redshift or Big Data Analytics
AWS June 2016 Webinar Series - Amazon Redshift or Big Data AnalyticsAmazon Web Services
 
Sql Server Query Parameterization
Sql Server Query ParameterizationSql Server Query Parameterization
Sql Server Query ParameterizationMindfire Solutions
 
Dev nexus 2017
Dev nexus 2017Dev nexus 2017
Dev nexus 2017Roy Russo
 
10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQL10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQLSatoshi Nagayasu
 
Building a Large Scale SEO/SEM Application with Apache Solr
Building a Large Scale SEO/SEM Application with Apache SolrBuilding a Large Scale SEO/SEM Application with Apache Solr
Building a Large Scale SEO/SEM Application with Apache SolrRahul Jain
 

Similar to Sql query performance analysis (20)

Index
IndexIndex
Index
 
Query parameterization
Query parameterizationQuery parameterization
Query parameterization
 
Index_2
Index_2Index_2
Index_2
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
 
POLARDB for MySQL - Parallel Query
POLARDB for MySQL - Parallel QueryPOLARDB for MySQL - Parallel Query
POLARDB for MySQL - Parallel Query
 
SAG_Indexing and Query Optimization
SAG_Indexing and Query OptimizationSAG_Indexing and Query Optimization
SAG_Indexing and Query Optimization
 
SQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET DeveloperSQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET Developer
 
AWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationAWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentation
 
How nebula graph index works
How nebula graph index worksHow nebula graph index works
How nebula graph index works
 
L6.sp17.pptx
L6.sp17.pptxL6.sp17.pptx
L6.sp17.pptx
 
Statistics
StatisticsStatistics
Statistics
 
AWS June 2016 Webinar Series - Amazon Redshift or Big Data Analytics
AWS June 2016 Webinar Series - Amazon Redshift or Big Data AnalyticsAWS June 2016 Webinar Series - Amazon Redshift or Big Data Analytics
AWS June 2016 Webinar Series - Amazon Redshift or Big Data Analytics
 
Statistics and Indexes Internals
Statistics and Indexes InternalsStatistics and Indexes Internals
Statistics and Indexes Internals
 
Sql Server Query Parameterization
Sql Server Query ParameterizationSql Server Query Parameterization
Sql Server Query Parameterization
 
JSSUG: SQL Sever Index Tuning
JSSUG: SQL Sever Index TuningJSSUG: SQL Sever Index Tuning
JSSUG: SQL Sever Index Tuning
 
Sql performance tuning
Sql performance tuningSql performance tuning
Sql performance tuning
 
Dev nexus 2017
Dev nexus 2017Dev nexus 2017
Dev nexus 2017
 
Cassandra training
Cassandra trainingCassandra training
Cassandra training
 
10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQL10 Reasons to Start Your Analytics Project with PostgreSQL
10 Reasons to Start Your Analytics Project with PostgreSQL
 
Building a Large Scale SEO/SEM Application with Apache Solr
Building a Large Scale SEO/SEM Application with Apache SolrBuilding a Large Scale SEO/SEM Application with Apache Solr
Building a Large Scale SEO/SEM Application with Apache Solr
 

More from Riteshkiit

Backup and restore
Backup and restoreBackup and restore
Backup and restoreRiteshkiit
 
Database index
Database indexDatabase index
Database indexRiteshkiit
 
Sql server introduction fundamental
Sql server introduction fundamentalSql server introduction fundamental
Sql server introduction fundamentalRiteshkiit
 
Order by and join
Order by and joinOrder by and join
Order by and joinRiteshkiit
 
Database design
Database designDatabase design
Database designRiteshkiit
 
Sql server JOIN
Sql server JOINSql server JOIN
Sql server JOINRiteshkiit
 

More from Riteshkiit (9)

Backup and restore
Backup and restoreBackup and restore
Backup and restore
 
Database index
Database indexDatabase index
Database index
 
Sql server introduction fundamental
Sql server introduction fundamentalSql server introduction fundamental
Sql server introduction fundamental
 
Order by and join
Order by and joinOrder by and join
Order by and join
 
Database design
Database designDatabase design
Database design
 
Addhoc query
Addhoc queryAddhoc query
Addhoc query
 
Sql server JOIN
Sql server JOINSql server JOIN
Sql server JOIN
 
Sql server 2
Sql server 2Sql server 2
Sql server 2
 
Topics
TopicsTopics
Topics
 

Recently uploaded

IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

Sql query performance analysis

  • 2. INDEX • 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 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 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 for particular key. We need indexing when cached query plan has: • WHERE , HAVING, ON clause (That is searching) • ORDER BY clause (That is sorting) • GROUP BY clause (This is grouping) etc.
  • 9. Table scan and Index 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 in B- Tree. • Leaf node of clustered index always keep actual data. • If we create table with primary key, sql server automatically creates clustered index on that table . • If clustered index has more than one partition then each partition has a B-tree.
  • 11. Index seek Time complexity of index seek is: O(log n)
  • 12. Types of scanning • Table scan: It is very slow scanning process and it is used only if table has not any clustered index. • Index scan: It is also slow scanning process. 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. • If a table has only five records which scanning will you follow?
  • 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. • Seek Predicate: It is condition in WHERE clause which is either key column or fully covered. • Object: It is name of source from where it getting the data. It can be heap, clustered index or non-clustered index. • Output list: It is name of the columns which are getting from the object.
  • 14. Non-clustered index • It is logical organization of data of table. A non-clustered index can be of two types. 1. Based on 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. • In heap leaf node of non-clustered index keeps RID.
  • 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 or updated 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