SlideShare a Scribd company logo
1 of 29
Download to read offline
SQL Server Query Parameterization


Query Tuning

Ritesh Kumar
Skype: mfs_ritesh
Blog: http://exacthelp.blogspot.com/
INDEX


Adhoc Query



Predicates Order



Execution Plan



Query Optimizer



Parameter Sniffing



Indexes



Statistics



Database Engine Tuning Advisor
Adhoc Query
q

Any non-parameterized queries are called addhoc queries.
For example :

q

SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 100

q

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

q

Compilation

q

Execution
Properties Of Addhoc Queries
q

Case sensitive

q

Space sensitive

q

Parameter sensitive 

q

Sql server treats two same sql queries of different parameters
as a two different sql statements. For example:

q

SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 1

q

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 applications since this faulty code will force to
delete cached query plans of other sql statements.
Predicates Order
q

Does order of predicates matters in WHERE clause?

q

WHERE vcLanguage = 'English' AND ntAge = 12

q

WHERE ntAge = 12 AND vcLanguage = 'English'
Execution Plan
Query Optimizer
Query Optimizer
The query optimizer in SQL Server is cost-based. It includes:
q

Cost for using different resources (CPU and IO)

q

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.
Parameter Sniffing


Sql server generates execution paln according to the first
parameter



This execution plan may bad for other parameters.

 
Solution:


Create multiples stored procedures.



Use optimizer for query hints.
What Is An Index ?
q

Index is a way to organize data to make searching, sorting
and grouping faster.

q

we need indexing when :

q

WHERE, ON, HAVING clause (Searching)

q

ORDER BY clause (Sorting)

q

GROUP BY clause (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
Types Of Index
q

Table without any index is called Heap

q

There are two type of index:

q

Clustered index

q

Non-Clustered index
Clustered Index


When we create a clustered index on any table physical
organization of table is changed.



Now data of table is stored as a balanced tree(B tree).

CREATE UNIQUE [CLUSTERED] INDEX <Name>
ON <ObjectName>(
<ColumnName>  [ASC | DESC ] [ ,...n ]
)
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.
Clustered Index


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



A table can have only one clustered index .



Physical order of rows of table is same as logical order of key
columns of clustered index.
Terms Of Execution Plan


Predicate: It is condition in WHERE clause which is either nonkey 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.

q

Heap

q

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 nonclustered 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.



The query optimizer determines when statistics might be out-ofdate by counting the number of data modifications since the
last statistics update and comparing the number of
modifications to a threshold.
Auto Create Statistics


Default setting of auto create statistics is ON.



It creates when:



Clustered and non clustered Index is created



Select query is executed.



Auto create and updates applies strictly to singlecolumn statistics.
Why Query 2 Is Performing Better
q

If we perform following operations on field of any table in
query predicate:

q

Using any system function or user defined function

q

Scalar operation like addition, multiplication etc.

q

Type casting

q

In this situation sql server query optimizer is not able to
estimate correct cardinality using statistics.
To Improve Cardinality


If possible, simplify expressions with constants in them.



If possible, don't perform any operation on the any field of a table
in WHERE Clause, ON Clause, HAVING Clause



Don't use local variables in WHERE Clause, ON Clause, HAVING
Clause. 



If there is any cross relationship among fields or there is a complex
expression in a field in a query predicates, it is better to create a
computed column and then create a non-clustered index on it.
To Improve Cardinality


If possible, don't update the value of parameters of a function or
stored procedure before using in sql statement



Use OPTIMIZE FOR clause when you want to optimize a sql query on
the basis of specific parameter value.



If you want to update the value parameter of a stored procedure or
a function create a similar procedure or function and execute it form
base procedure or function by passing the updated value as a
parameter. 



Create user defined multi column statistics if query predicates have
more than one fields of a table.
SQL Server Tools


Sql query profiler



Database Tuning Advisor



Client Statistics



Resource Governor



Data Collections
THANK YOU

More Related Content

What's hot

Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Mahesh Tibrewal
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory MappingQundeel
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Abdul Khan
 
3.6 radix sort
3.6 radix sort3.6 radix sort
3.6 radix sortKrish_ver2
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structuresKuber Chandra
 
Array 2
Array 2Array 2
Array 2Abbott
 
Array ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data StructureArray ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data StructureAkash Gaur
 
Query hierarchical data the easy way, with CTEs
Query hierarchical data the easy way, with CTEsQuery hierarchical data the easy way, with CTEs
Query hierarchical data the easy way, with CTEsMariaDB plc
 
List Data Structure
List Data StructureList Data Structure
List Data StructureZidny Nafan
 
Counting Sort Lowerbound
Counting Sort LowerboundCounting Sort Lowerbound
Counting Sort Lowerbounddespicable me
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queueTareq Hasan
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for publiciqbalphy1
 

What's hot (20)

Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!
 
Radix sort
Radix sortRadix sort
Radix sort
 
Unit 3 stack
Unit 3   stackUnit 3   stack
Unit 3 stack
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
 
Data structures
Data structuresData structures
Data structures
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
3.6 radix sort
3.6 radix sort3.6 radix sort
3.6 radix sort
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structures
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
Array 2
Array 2Array 2
Array 2
 
Array ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data StructureArray ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data Structure
 
Query hierarchical data the easy way, with CTEs
Query hierarchical data the easy way, with CTEsQuery hierarchical data the easy way, with CTEs
Query hierarchical data the easy way, with CTEs
 
List Data Structure
List Data StructureList Data Structure
List Data Structure
 
Counting Sort Lowerbound
Counting Sort LowerboundCounting Sort Lowerbound
Counting Sort Lowerbound
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queue
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
SQL Issue
SQL IssueSQL Issue
SQL Issue
 
Radix Sort
Radix SortRadix Sort
Radix Sort
 
15 unionfind
15 unionfind15 unionfind
15 unionfind
 

Viewers also liked

MS SQL Server 2008, Implementation and Maintenance
MS SQL Server 2008, Implementation and MaintenanceMS SQL Server 2008, Implementation and Maintenance
MS SQL Server 2008, Implementation and MaintenanceVitaliy Fursov
 
Sigir12 tutorial: Query Perfromance Prediction for IR
Sigir12 tutorial: Query Perfromance Prediction for IRSigir12 tutorial: Query Perfromance Prediction for IR
Sigir12 tutorial: Query Perfromance Prediction for IRDavid Carmel
 
Find and be Found: Information Retrieval at LinkedIn
Find and be Found: Information Retrieval at LinkedInFind and be Found: Information Retrieval at LinkedIn
Find and be Found: Information Retrieval at LinkedInDaniel Tunkelang
 
Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...
Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...
Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...Abhimanyu Lad
 
Er diagram practical examples
Er diagram practical examplesEr diagram practical examples
Er diagram practical examplesRahul Khanwani
 
Password based door locking system
Password based door locking systemPassword based door locking system
Password based door locking systemArjun Singh
 
Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)Mudasir Qazi
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship DiagramShakila Mahjabin
 
How to Draw an Effective ER diagram
How to Draw an Effective ER diagramHow to Draw an Effective ER diagram
How to Draw an Effective ER diagramTech_MX
 
Data encryption, Description, DES
Data encryption, Description, DESData encryption, Description, DES
Data encryption, Description, DESHuawei Technologies
 
Exploiting Wikipedia for Information Retrieval Tasks, SIGIR Tutorial
Exploiting Wikipedia for Information Retrieval Tasks, SIGIR TutorialExploiting Wikipedia for Information Retrieval Tasks, SIGIR Tutorial
Exploiting Wikipedia for Information Retrieval Tasks, SIGIR TutorialVictor Makarenkov
 
Encryption presentation final
Encryption presentation finalEncryption presentation final
Encryption presentation finaladrigee12
 
Entity relationship diagram (erd)
Entity relationship diagram (erd)Entity relationship diagram (erd)
Entity relationship diagram (erd)tameemyousaf
 

Viewers also liked (20)

MS SQL Server 2008, Implementation and Maintenance
MS SQL Server 2008, Implementation and MaintenanceMS SQL Server 2008, Implementation and Maintenance
MS SQL Server 2008, Implementation and Maintenance
 
Sigir12 tutorial: Query Perfromance Prediction for IR
Sigir12 tutorial: Query Perfromance Prediction for IRSigir12 tutorial: Query Perfromance Prediction for IR
Sigir12 tutorial: Query Perfromance Prediction for IR
 
Find and be Found: Information Retrieval at LinkedIn
Find and be Found: Information Retrieval at LinkedInFind and be Found: Information Retrieval at LinkedIn
Find and be Found: Information Retrieval at LinkedIn
 
Password based door locksystem
Password  based door locksystemPassword  based door locksystem
Password based door locksystem
 
Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...
Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...
Fast, Lenient, and Accurate – Building Personalized Instant Search Experience...
 
Er diagram practical examples
Er diagram practical examplesEr diagram practical examples
Er diagram practical examples
 
Erd examples
Erd examplesErd examples
Erd examples
 
Password based door locking system
Password based door locking systemPassword based door locking system
Password based door locking system
 
Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)Database - Entity Relationship Diagram (ERD)
Database - Entity Relationship Diagram (ERD)
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship Diagram
 
How to Draw an Effective ER diagram
How to Draw an Effective ER diagramHow to Draw an Effective ER diagram
How to Draw an Effective ER diagram
 
Data encryption, Description, DES
Data encryption, Description, DESData encryption, Description, DES
Data encryption, Description, DES
 
Cryptography
CryptographyCryptography
Cryptography
 
Cryptography
CryptographyCryptography
Cryptography
 
Exploiting Wikipedia for Information Retrieval Tasks, SIGIR Tutorial
Exploiting Wikipedia for Information Retrieval Tasks, SIGIR TutorialExploiting Wikipedia for Information Retrieval Tasks, SIGIR Tutorial
Exploiting Wikipedia for Information Retrieval Tasks, SIGIR Tutorial
 
Erd practice exercises
Erd practice exercisesErd practice exercises
Erd practice exercises
 
Data mining
Data miningData mining
Data mining
 
Encryption presentation final
Encryption presentation finalEncryption presentation final
Encryption presentation final
 
Project ppt
Project pptProject ppt
Project ppt
 
Entity relationship diagram (erd)
Entity relationship diagram (erd)Entity relationship diagram (erd)
Entity relationship diagram (erd)
 

Similar to Sql Server Query Parameterization

Query parameterization
Query parameterizationQuery parameterization
Query parameterizationRiteshkiit
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysisRiteshkiit
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statementsxKinAnx
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysisRiteshkiit
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance OptimizationMindfire Solutions
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-dbuncleRhyme
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guidelineSidney Chen
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluationavniS
 
K-Means Algorithm Implementation In python
K-Means Algorithm Implementation In pythonK-Means Algorithm Implementation In python
K-Means Algorithm Implementation In pythonAfzal Ahmad
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the ServerdevObjective
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLMárton Kodok
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain PlanMaria Colgan
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343Edgar Alejandro Villegas
 

Similar to Sql Server Query Parameterization (20)

Query parameterization
Query parameterizationQuery parameterization
Query parameterization
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guideline
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
 
Statistics
StatisticsStatistics
Statistics
 
K-Means Algorithm Implementation In python
K-Means Algorithm Implementation In pythonK-Means Algorithm Implementation In python
K-Means Algorithm Implementation In python
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
 
Chapter15
Chapter15Chapter15
Chapter15
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain Plan
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 

More from Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
 
diet management app
diet management appdiet management app
diet management app
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
 
ELMAH
ELMAHELMAH
ELMAH
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
 

Recently uploaded

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Recently uploaded (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Sql Server Query Parameterization

  • 1. SQL Server Query Parameterization  Query Tuning Ritesh Kumar Skype: mfs_ritesh Blog: http://exacthelp.blogspot.com/
  • 2. INDEX  Adhoc Query  Predicates Order  Execution Plan  Query Optimizer  Parameter Sniffing  Indexes  Statistics  Database Engine Tuning Advisor
  • 3. Adhoc Query q Any non-parameterized queries are called addhoc queries. For example : q SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 100 q In sql server if we execute a sql query it goes through two steps just like any other programming languages: q Compilation q Execution
  • 4. Properties Of Addhoc Queries q Case sensitive q Space sensitive q Parameter sensitive  q Sql server treats two same sql queries of different parameters as a two different sql statements. For example: q SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 1 q SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 2
  • 5. 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 applications since this faulty code will force to delete cached query plans of other sql statements.
  • 6. Predicates Order q Does order of predicates matters in WHERE clause? q WHERE vcLanguage = 'English' AND ntAge = 12 q WHERE ntAge = 12 AND vcLanguage = 'English'
  • 9. Query Optimizer The query optimizer in SQL Server is cost-based. It includes: q Cost for using different resources (CPU and IO) q 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.
  • 10. Parameter Sniffing  Sql server generates execution paln according to the first parameter  This execution plan may bad for other parameters.   Solution:  Create multiples stored procedures.  Use optimizer for query hints.
  • 11. What Is An Index ? q Index is a way to organize data to make searching, sorting and grouping faster. q we need indexing when : q WHERE, ON, HAVING clause (Searching) q ORDER BY clause (Sorting) q GROUP BY clause (Grouping) etc.
  • 12. 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
  • 13. Types Of Index q Table without any index is called Heap q There are two type of index: q Clustered index q Non-Clustered index
  • 14. Clustered Index  When we create a clustered index on any table physical organization of table is changed.  Now data of table is stored as a balanced tree(B tree). CREATE UNIQUE [CLUSTERED] INDEX <Name> ON <ObjectName>( <ColumnName>  [ASC | DESC ] [ ,...n ] )
  • 15.
  • 16. 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.
  • 17. Clustered Index  If we create table with primary key, sql server automatically creates clustered index on that table  A table can have only one clustered index .  Physical order of rows of table is same as logical order of key columns of clustered index.
  • 18. Terms Of Execution Plan  Predicate: It is condition in WHERE clause which is either nonkey 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.
  • 19. Non-Clustered Index  It is logical organization of data of table. A non-clustered index can be of two types. q Heap q 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 nonclustered index keeps RID which unique of each row of table.
  • 22. 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.
  • 23. 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.  The query optimizer determines when statistics might be out-ofdate by counting the number of data modifications since the last statistics update and comparing the number of modifications to a threshold.
  • 24. Auto Create Statistics  Default setting of auto create statistics is ON.  It creates when:  Clustered and non clustered Index is created  Select query is executed.  Auto create and updates applies strictly to singlecolumn statistics.
  • 25. Why Query 2 Is Performing Better q If we perform following operations on field of any table in query predicate: q Using any system function or user defined function q Scalar operation like addition, multiplication etc. q Type casting q In this situation sql server query optimizer is not able to estimate correct cardinality using statistics.
  • 26. To Improve Cardinality  If possible, simplify expressions with constants in them.  If possible, don't perform any operation on the any field of a table in WHERE Clause, ON Clause, HAVING Clause  Don't use local variables in WHERE Clause, ON Clause, HAVING Clause.   If there is any cross relationship among fields or there is a complex expression in a field in a query predicates, it is better to create a computed column and then create a non-clustered index on it.
  • 27. To Improve Cardinality  If possible, don't update the value of parameters of a function or stored procedure before using in sql statement  Use OPTIMIZE FOR clause when you want to optimize a sql query on the basis of specific parameter value.  If you want to update the value parameter of a stored procedure or a function create a similar procedure or function and execute it form base procedure or function by passing the updated value as a parameter.   Create user defined multi column statistics if query predicates have more than one fields of a table.
  • 28. SQL Server Tools  Sql query profiler  Database Tuning Advisor  Client Statistics  Resource Governor  Data Collections