SlideShare a Scribd company logo
Sql Server Query
Parameterization
Query Tuning
INDEX
   Adhoc Query
   Predicates Order
   Execution Plan
   Query Optimizer
   Parameter Sniffing
   Indexes
   Statistics
   Database Engine Tuning Advisor
Adhoc Query
   Any non-Parameterized queries 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:

   Compilation
   Execution
Properties Of Addhoc
Queries
   Case sensitive
   Space sensitive
   Parameter sensitive

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

   SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 1
   SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 2

Recommended for you

Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries

This document discusses various data types and SQL commands used in Oracle databases. It covers: - Common data types like CHAR, VARCHAR2, NUMBER, DATE, LONG, RAW, BLOB, CLOB and how they store data. - SQL commands for data definition (CREATE, ALTER, DROP), data manipulation (SELECT, INSERT, UPDATE, DELETE), and integrity constraints (PRIMARY KEY, FOREIGN KEY). - Functions for calculations, string operations and data retrieval from tables.

Oracle Course
Oracle CourseOracle Course
Oracle Course

The document provides an overview of database concepts and features in Oracle, including fundamentals like data grouping and relationships, as well as operations on tables like insert, update, delete. It also covers queries with filters, joins, and aggregations, as well as other objects like views, sequences, indexes, triggers, and stored procedures. The document is intended as training material for the Oracle database.

Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL

This document provides information about an upcoming SQL Saturday Night event on March 30, 2013 that will focus on using T-SQL. The presentation will be recorded so that those unable to attend can view it later. Attendees are asked to change their virtual cards to a specific color if they are unable to hear the presenter. The presentation will be free and begin in 1 minute.

sql saturday nights
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 statements.
Predicates Order
   Does order of predicates in WHERE clause
    matters?

   WHERE vcLanguage = 'English' AND ntAge = 12


   WHERE ntAge = 12 AND vcLanguage = 'English'
Execution Plan
Query Optimizer

Recommended for you

Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net

This chapter discusses how to connect to and manipulate SQL Server databases from ASP.NET applications. It covers using classes in the System.Data.SqlClient namespace to connect to databases and execute SQL commands. Methods like ExecuteReader, ExecuteNonQuery and SqlDataReader are used to retrieve and modify data. The chapter also describes how to create, update and delete databases and tables by executing SQL statements with ASP.NET code.

synapseindia complaintssynapseindia reviewssynapseindia sharepoint development
Oracle foreign key missing index - a single index can boost performance
Oracle foreign key missing index - a single index can boost performanceOracle foreign key missing index - a single index can boost performance
Oracle foreign key missing index - a single index can boost performance

In Oracle databases, a foreign key does not require that the column being restricted should have an index. Update and Delete operations on referenced tables may have a heavy impact in performance, overloading the server. A single index can reduce the cost of these DML operations.

tableoracledatabase
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics

This document provides an overview and introduction to Oracle SQL basics. It covers topics such as installing Oracle software like the database, Java SDK, and SQL Developer tool. It then discusses database concepts like what a database and table are. It also covers database fundamentals including SQL queries, functions, joins, constraints, views and other database objects. The document provides examples and explanations of SQL statements and database components.

sqlsql basicsoracle
Query Optimizer
The query optimizer in SQL Server is cost-based. It includes:

   Cost for using different resources (CPU and IO)
   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 ?
   Index is a way to organize data to make
    searching, sorting and grouping fasters
   we need indexing when :

   WHERE, ON, HAVING clause (Searching)
   ORDER BY clause (Sorting)
   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

Recommended for you

Sql killedserver
Sql killedserverSql killedserver
Sql killedserver

This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and analyzed. The presenter aims to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.

sql
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements

This document discusses transactions in SQL Server. It introduces transactions and their relevance in ensuring data integrity when multiple tables need to be updated together. Transactions group a set of database operations so that if any operation fails, all operations are rolled back. The document demonstrates creating a transaction using START TRANSACTION, COMMIT TRANSACTION, and ROLLBACK TRANSACTION statements. It also shows handling transactions within try/catch blocks so that failures cause a rollback. Transactions ensure atomicity and integrity by committing all operations together as a single unit, or rolling them all back if any fail.

MS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data miningMS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data mining

This document discusses programming SQL Server data mining with Analysis Management Objects (AMO) and stored procedures. It describes how to create mining structures and models using AMO, including defining columns, updating objects, and processing models. It also explains how to create, execute, and debug stored procedures for adding business logic, including registering assemblies, setting permissions, and attaching to processes for debugging. The goal is to provide an overview of programming options for data mining with SQL Server.

sql server
Types Of Index
   Table without any index is called Heap

   There are two type of index:

   Clustered index
   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 ]
)
Query parameterization
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.

Recommended for you

cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features

This is a very brief overview for cPanel customers on MySQL 8.0 and these are my top 7 (seven) new features.

mysqlsqlnosql
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server

MS SQL SERVER IS Database Management System created by Microsoft Corporation. This slide shortly describe MS SQL SERVER common functionality.

hoquemssqlservermojibulhouqe
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014

The document discusses new improvements to the parser and optimizer in MySQL 5.7. Key points include: 1) The parser and optimizer were refactored for improved maintainability and stability. Parsing was separated from optimization and execution. 2) The cost model was improved with better record estimation for joins, configurable cost constants, and additional explain output. 3) A new query rewrite plugin allows rewriting queries without changing application code.

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

    Heap
    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

Recommended for you

Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures

This document discusses stored procedures in SQL Server. It begins by explaining that stored procedures allow encapsulation of repetitive tasks and are stored in the database data dictionary. It then shows how stored procedures reduce network traffic and client-server communication compared to individual SQL statements. The document provides examples of how to create a stored procedure using CREATE PROCEDURE and how to call it using EXEC. It notes advantages like precompiled execution, reduced traffic, code reuse, and security control. It also demonstrates using parameters, loops, conditions and variables inside stored procedures.

Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms

This document discusses how to speed up queries in MySQL through the proper use of indexes, histograms, and other techniques. It begins by explaining that the MySQL optimizer tries to determine the most efficient way to execute queries by considering different query plans. The optimizer relies on statistics about column distributions to estimate query costs. The document then discusses using EXPLAIN to view and analyze query plans, and how indexes can improve query performance by allowing faster data retrieval through secondary indexes and other index types. Proper index selection and column data types are important to allow the optimizer to use indexes efficiently.

mysqldatabasedata
Optimizing queries MySQL
Optimizing queries MySQLOptimizing queries MySQL
Optimizing queries MySQL

This presentation focuses on optimization of queries in MySQL from developer’s perspective. Developers should care about the performance of the application, which includes optimizing SQL queries. It shows the execution plan in MySQL and explain its different formats - tabular, TREE and JSON/visual explain plans. Optimizer features like optimizer hints and histograms as well as newer features like HASH joins, TREE explain plan and EXPLAIN ANALYZE from latest releases are covered. Some real examples of slow queries are included and their optimization explained.

mysqlsqlquery optimization
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-of-date 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
    single-column statistics.

Recommended for you

Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors

This document provides an overview of Android application development training on accessing and manipulating data using SQLite databases on Android. It covers topics like what SQLite is, creating and connecting to databases, setting database properties, creating tables, inserting, updating, and deleting records from the databases using ContentValues and SQLiteDatabase methods. Code examples are provided for each topic.

android training class in cochin_kochi_keralaandroid training in cochin_kochi_keralaandroid training institute in cochin_kochi_kerala
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE

This presentation focuses on two of the new features in MySQL 8.0.18: hash joins and EXPLAIN ANALYZE. It covers how these features work, both on the surface and on the inside, and how you can use them to improve your queries and make them go faster. Both features are the result of major refactoring of how the MySQL executor works. In addition to explaining and demonstrating the features themselves, the presentation looks at how the investment in a new iterator based executor prepares MySQL for a future with faster queries, greater plan flexibility and even more SQL features.

mysqlsqlhash join
You are all dead to me
You are all dead to meYou are all dead to me
You are all dead to me

This document discusses how the author's time is extraordinarily valuable and feels it is being wasted. The author concludes that whoever is wasting their time is now "dead to me" and they should refer to the previous bullet points listed.

Why Query 2 Is Performing
Better
   If we perform following operations on field of
    any table in query predicate:

   Using any system function or user defined
    function
   Scalar operation like addition, multiplication
    etc.
   Type casting

   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

Recommended for you

Estudio benchmark publicidad digital mayor rendimiento por media mind
Estudio benchmark publicidad digital mayor rendimiento por media mindEstudio benchmark publicidad digital mayor rendimiento por media mind
Estudio benchmark publicidad digital mayor rendimiento por media mind

MediaMind, proveedor líder mundial de soluciones integradas de publicidad online, ha presentado su estudio comparativo mundial (benchmark) de publicidad online.

publicidad onlinepublicidad en lineapublicidad
E government 2012 Colombia
E government 2012 ColombiaE government 2012 Colombia
E government 2012 Colombia

This document is the United Nations E-Government Survey 2012. It discusses how e-government can advance sustainable development and be more responsive, citizen-centric, and socially inclusive. The survey found that while e-government has helped promote transparency and accountability, more needs to be done to reduce digital divides and increase access for vulnerable groups. Cooperation between governments, funding, and innovations like mobile services will help e-government better serve people.

gobierno electronicoe-governmentcolombia
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis

The document discusses SQL query performance analysis. It covers topics like the query optimizer, execution plans, statistics analysis, and different types of queries and scanning. The query optimizer is cost-based and determines the most efficient execution plan using cardinality estimates and cost models. Addhoc queries are non-parameterized queries that SQL Server treats differently than prepared queries. Execution plans show the steps and methods used to retrieve and process data. Statistics help the optimizer generate accurate cardinality estimates to pick high-performing plans.

THANK YOU

More Related Content

What's hot

PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
Dave Stokes
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & Histograms
Dave Stokes
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
Manikanda kumar
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
PRAKHAR JHA
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
rspaike
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
Antonios Chatzipavlis
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
Synapseindiappsdevelopment
 
Oracle foreign key missing index - a single index can boost performance
Oracle foreign key missing index - a single index can boost performanceOracle foreign key missing index - a single index can boost performance
Oracle foreign key missing index - a single index can boost performance
Carlos Oliveira
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
Dhananjay Goel
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
ColdFusionConference
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
MS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data miningMS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data mining
DataminingTools Inc
 
cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
Dave Stokes
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
Md.Mojibul Hoque
 
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014
Mysql User Camp
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dave Stokes
 
Optimizing queries MySQL
Optimizing queries MySQLOptimizing queries MySQL
Optimizing queries MySQL
Georgi Sotirov
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
Norvald Ryeng
 

What's hot (20)

PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & Histograms
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
 
Oracle foreign key missing index - a single index can boost performance
Oracle foreign key missing index - a single index can boost performanceOracle foreign key missing index - a single index can boost performance
Oracle foreign key missing index - a single index can boost performance
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
MS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data miningMS SQL SERVER: Programming sql server data mining
MS SQL SERVER: Programming sql server data mining
 
cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Optimizer overviewoow2014
Optimizer overviewoow2014Optimizer overviewoow2014
Optimizer overviewoow2014
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
 
Optimizing queries MySQL
Optimizing queries MySQLOptimizing queries MySQL
Optimizing queries MySQL
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZEMySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
MySQL 8.0.18 latest updates: Hash join and EXPLAIN ANALYZE
 

Viewers also liked

You are all dead to me
You are all dead to meYou are all dead to me
You are all dead to me
zedgrangerson
 
Estudio benchmark publicidad digital mayor rendimiento por media mind
Estudio benchmark publicidad digital mayor rendimiento por media mindEstudio benchmark publicidad digital mayor rendimiento por media mind
Estudio benchmark publicidad digital mayor rendimiento por media mind
Comercio Electronico
 
E government 2012 Colombia
E government 2012 ColombiaE government 2012 Colombia
E government 2012 Colombia
Comercio Electronico
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
Riteshkiit
 
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
Comercio Electronico
 
Sql server 2
Sql server 2Sql server 2
Sql server 2
Riteshkiit
 
Sql server introduction fundamental
Sql server introduction fundamentalSql server introduction fundamental
Sql server introduction fundamental
Riteshkiit
 
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y TravelReporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
Comercio Electronico
 

Viewers also liked (8)

You are all dead to me
You are all dead to meYou are all dead to me
You are all dead to me
 
Estudio benchmark publicidad digital mayor rendimiento por media mind
Estudio benchmark publicidad digital mayor rendimiento por media mindEstudio benchmark publicidad digital mayor rendimiento por media mind
Estudio benchmark publicidad digital mayor rendimiento por media mind
 
E government 2012 Colombia
E government 2012 ColombiaE government 2012 Colombia
E government 2012 Colombia
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
 
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
Google Analytics Bootcamp Bogota Junio 28 2012 Dia 4
 
Sql server 2
Sql server 2Sql server 2
Sql server 2
 
Sql server introduction fundamental
Sql server introduction fundamentalSql server introduction fundamental
Sql server introduction fundamental
 
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y TravelReporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
Reporte Cámara Colombiana de Comercio Electrónico Retail, Banking y Travel
 

Similar to Query parameterization

Sql Server Query Parameterization
Sql Server Query ParameterizationSql Server Query Parameterization
Sql Server Query Parameterization
Mindfire Solutions
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
Riteshkiit
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
Mindfire Solutions
 
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
xKinAnx
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guideline
Sidney Chen
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
paulguerin
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
devObjective
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
guest9d79e073
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
Mark Ginnebaugh
 
Application sql issues_and_tuning
Application sql issues_and_tuningApplication sql issues_and_tuning
Application sql issues_and_tuning
Anil Pandey
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
Anurag Srivastava
 
Module08
Module08Module08
Module08
guest5c8fba1
 
Module08
Module08Module08
Module08
Sridhar P
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
avniS
 
3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql
Łukasz Grala
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
Dave Stokes
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
KareemBullard1
 
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Dave Stokes
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain Plan
Maria Colgan
 
Database testing
Database testingDatabase testing
Database testing
Pesara Swamy
 

Similar to Query parameterization (20)

Sql Server Query Parameterization
Sql Server Query ParameterizationSql Server Query Parameterization
Sql Server Query Parameterization
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
 
MySQL Performance Optimization
MySQL Performance OptimizationMySQL Performance Optimization
MySQL Performance Optimization
 
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 tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guideline
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
My SQL Skills Killed the Server
My SQL Skills Killed the ServerMy SQL Skills Killed the Server
My SQL Skills Killed the Server
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09
 
Application sql issues_and_tuning
Application sql issues_and_tuningApplication sql issues_and_tuning
Application sql issues_and_tuning
 
MySQL performance tuning
MySQL performance tuningMySQL performance tuning
MySQL performance tuning
 
Module08
Module08Module08
Module08
 
Module08
Module08Module08
Module08
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
 
3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
 
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
 
Part3 Explain the Explain Plan
Part3 Explain the Explain PlanPart3 Explain the Explain Plan
Part3 Explain the Explain Plan
 
Database testing
Database testingDatabase testing
Database testing
 

More from Riteshkiit

Backup and restore
Backup and restoreBackup and restore
Backup and restore
Riteshkiit
 
Database index
Database indexDatabase index
Database index
Riteshkiit
 
Index_2
Index_2Index_2
Index_2
Riteshkiit
 
Order by and join
Order by and joinOrder by and join
Order by and join
Riteshkiit
 
Sql server introduction
Sql server introductionSql server introduction
Sql server introduction
Riteshkiit
 
Database design
Database designDatabase design
Database design
Riteshkiit
 
Statistics
StatisticsStatistics
Statistics
Riteshkiit
 
Index
IndexIndex
Index
Riteshkiit
 
Addhoc query
Addhoc queryAddhoc query
Addhoc query
Riteshkiit
 
Sql server JOIN
Sql server JOINSql server JOIN
Sql server JOIN
Riteshkiit
 
Topics
TopicsTopics
Topics
Riteshkiit
 

More from Riteshkiit (11)

Backup and restore
Backup and restoreBackup and restore
Backup and restore
 
Database index
Database indexDatabase index
Database index
 
Index_2
Index_2Index_2
Index_2
 
Order by and join
Order by and joinOrder by and join
Order by and join
 
Sql server introduction
Sql server introductionSql server introduction
Sql server introduction
 
Database design
Database designDatabase design
Database design
 
Statistics
StatisticsStatistics
Statistics
 
Index
IndexIndex
Index
 
Addhoc query
Addhoc queryAddhoc query
Addhoc query
 
Sql server JOIN
Sql server JOINSql server JOIN
Sql server JOIN
 
Topics
TopicsTopics
Topics
 

Query parameterization

  • 2. INDEX  Adhoc Query  Predicates Order  Execution Plan  Query Optimizer  Parameter Sniffing  Indexes  Statistics  Database Engine Tuning Advisor
  • 3. Adhoc Query  Any non-Parameterized queries 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:  Compilation  Execution
  • 4. Properties Of Addhoc Queries  Case sensitive  Space sensitive  Parameter sensitive  Sql server treats two same sql queries of different parameters as a two different sql statements. For example:  SELECT MsgID, Severity FROM SqlMessage WHERE MsgID = 1  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 application since this faulty code will force to delete cached query plans of other sql statements.
  • 6. Predicates Order  Does order of predicates in WHERE clause matters?  WHERE vcLanguage = 'English' AND ntAge = 12  WHERE ntAge = 12 AND vcLanguage = 'English'
  • 9. Query Optimizer The query optimizer in SQL Server is cost-based. It includes:  Cost for using different resources (CPU and IO)  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 ?  Index is a way to organize data to make searching, sorting and grouping fasters  we need indexing when :  WHERE, ON, HAVING clause (Searching)  ORDER BY clause (Sorting)  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  Table without any index is called Heap  There are two type of index:  Clustered index  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 ] )
  • 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 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.
  • 19. Non-Clustered Index  It is logical organization of data of table. A non-clustered index can be of two types.  Heap  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.
  • 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-of-date 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 single-column statistics.
  • 25. Why Query 2 Is Performing Better  If we perform following operations on field of any table in query predicate:  Using any system function or user defined function  Scalar operation like addition, multiplication etc.  Type casting  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