SlideShare a Scribd company logo
11
Query Execution Plan
• Whenever an SQL statement is issued in SQL Server engine, it first
determines the best possible way to execute it.
• The Query Optimizer (a system that generates the optimal query
execution plan before executing the query) uses several information
like the data distribution statistics, index structure, metadata, and
other information to analyse several possible execution plans and
finally select one that is likely to be the best execution plan most of
the time.
• We can use SQL Server Management Studio to preview and analyze
the estimated execution plan for the query that you are going to issue
Most read
12
Query Execution Plan Preview
Most read
14
Steps in T-SQL Refactoring
• Analysing the indexes
• Analysing the query execution plan
• Implementing some best practices
• Implement computed columns and create indexes if necessary
• Create Views and Indexed Views if Necessary
Most read
Query Optimization
• We develop and deploy web apps. It is much faster in development
environment and in test server. However, the web app is
subsequently degrading in performance.
• When we investigating, we discovered that the production database
was performing extremely slowly when the application was trying to
access/update data.
• Looking into the database, we find that the database tables have
grown large in size and some of them were containing hundreds of
thousands of rows. We found that the submission process was taking
5 long minutes to complete, whereas it used to take only 2/3 seconds
to complete in the test server before production launch.
• Here comes query optimization
What is Indexing?
• A database index is a data structure that improves the speed of data
retrieval operations on a database table at the cost of additional
writes and storage space to maintain the index data structure.
• Indexes are used to quickly locate data without having to search
every row in a database table every time a database table is
accessed.
• Indexes can be created using one or more columns of a database
table, providing the basis for both rapid random lookups and efficient
access of ordered records.
Index Tree
Cluster & Non-Cluster Index
• Cluster Index will be created automatically when you add a Primary
Key column in a table. Eg., ProductID
• Only one cluster Index can be created for a table
• Non-Cluster Index will be created to non-primary key columns
• It is advisable to have maximum of 5 non-cluster index per table
Non-Cluster Index should be created to
Columns?
• Frequently used in the search criteria
• Used to join other tables
• Used as foreign key fields
• Of having high selectivity (column which returns a low percentage (0-
5%) of rows from a total number of rows on a particular value)
• Used in the ORDER BY clause
• Of type XML (primary and secondary indexes need to be created;
more on this in the coming articles)
Index Fragmentation
• Index fragmentation is a situation where index pages split due to
heavy insert, update, and delete operations on the tables in the
database. If indexes have high fragmentation, either
scanning/seeking the indexes takes much time, or the indexes are not
used at all (resulting in table scan) while executing queries. Thus, data
retrieval operations perform slow
Types of Index Fragmentation
• Internal Fragmentation: Occurs due to data deletion/update
operations in the index pages which end up in the distribution of data
as a sparse matrix in the index/data pages (creates lots of empty rows
in the pages). Also results in an increase of index/data pages that
increases query execution time.
• External Fragmentation: Occurs due to data insert/update operations
in the index/data pages which end up in page splitting and allocation
of new index/data pages that are not contiguous in the file system.
That reduces performance in determining the query result where
ranges are specified in the "where" clauses.
Defragmenting Indexes
Reorganize indexes: execute the following command to do this:
ALTER INDEX ALL ON TableName REORGANIZE
Rebuild indexes: execute the following command to do this:
ALTER INDEX ALL ON TableName REBUILD WITH
(FILLFACTOR=90,ONLINE=ON)
When to reorganize and when to rebuild indexes?
• You should "reorganize" indexes when the External Fragmentation
value for the corresponding index is between 10-15 and the Internal
Fragmentation value is between 60-75. Otherwise, you should rebuild
indexes.
Move T-SQL from App to Database
• We use ORM that generates all the SQL for us on the fly
• Moving SQL from application and implementing them using Stored
Procedures/Views/Functions/Triggers will enable you to eliminate
any duplicate SQL in your application. This will also ensure re-
usability of your TSQL codes.
• Implementing all TSQL using database objects will enable you to
analyse the TSQLs more easily to find possible inefficient codes that
are responsible for the slow performance. Also, this will let you
manage your TSQL codes from a central point.
• Doing this will also enable you to re-factor your TSQL codes to take
advantage of some advanced indexing techniques.
Identify inefficient TSQL, re-factor, and
apply best practices
• Avoid unnecessary columns in the SELECT list and unnecessary tables in join
conditions.
• Do not use the COUNT() aggregate in a subquery to do an existence check
• Avoid joining between two types of columns
• TSQL using "Set based approach" rather than "Procedural approach“(use of
Cursor or UDF to process rows in a result set)
• Avoid dynamic SQL
• Avoid the use of temporary tables
• Implement a lazy loading strategy for large objects
• Avoid the use of triggers
• Use views for re-using complex TSQL blocks. Do not use views that retrieve
data from a single table only
Query Execution Plan
• Whenever an SQL statement is issued in SQL Server engine, it first
determines the best possible way to execute it.
• The Query Optimizer (a system that generates the optimal query
execution plan before executing the query) uses several information
like the data distribution statistics, index structure, metadata, and
other information to analyse several possible execution plans and
finally select one that is likely to be the best execution plan most of
the time.
• We can use SQL Server Management Studio to preview and analyze
the estimated execution plan for the query that you are going to issue
Query Execution Plan Preview
Information Available on Query Execution
Plan
• Table Scan: Occurs when the corresponding table does not have a clustered index.
Most likely, creating a clustered index or defragmenting index will enable you to get
rid of it.
• Clustered Index Scan: Sometimes considered equivalent to Table Scan. Takes place
when a non-clustered index on an eligible column is not available. Most of the
time, creating a non-clustered index will enable you to get rid of it.
• Hash Join: The most expensive joining methodology. This takes place when the
joining columns between two tables are not indexed. Creating indexes on those
columns will enable you to get rid of it.
• Nested Loops: Most cases, this happens when a non-clustered index does not
include (Cover) a column that is used in the SELECT column list. In this case, for
each member in the non-clustered index column, the database server has to seek
into the clustered index to retrieve the other column value specified in the SELECT
list. Creating a covered index will enable you to get rid of it.
• RID Lookup: Takes place when you have a non-clustered index but the same table
does not have any clustered index. In this case, the database engine has to look up
the actual row using the row ID, which is an expensive operation. Creating a
clustered index on the corresponding table would enable you to get rid of it.
Steps in T-SQL Refactoring
• Analysing the indexes
• Analysing the query execution plan
• Implementing some best practices
• Implement computed columns and create indexes if necessary
• Create Views and Indexed Views if Necessary
Indexed Views
• Views don't give you any significant performance benefit
• Views are nothing but compiled queries, and Views just can't
remember any result set
• We can create indexed view so that it can remember the result set for
the SELECT query it is composed of
CREATE VIEW dbo.vOrderDetails
WITH SCHEMABINDING
AS
SELECT...
De-normalization
• If you are designing a database for an OLTA system (Online
Transaction Analytical system that is mainly a data warehouse which
is optimized for read-only queries), you should apply heavy de-
normalizing and indexing in your database. i.e., the same data will be
stored across different tables, but the reporting and data analytical
queries would run very faster.
• If you are designing a database for an OLTP system (Online
Transaction Processing System that is mainly a transactional system
where mostly data update operations take place [that is,
INSERT/UPDATE/DELETE]), implement at least 1st, 2nd, and 3rd
Normal forms so that we can minimize data redundancy, and thus
minimize data storage and increase manageability.
History Tables
• In an application, if we have some data retrieval operation (say,
reporting) that periodically runs on a time period, and if the process
involves tables that are large in size having normalized structure, we
can consider moving data periodically from transactional normalized
tables into a de-normalized, heavily indexed, single history table.
• We can also create a scheduled operation in database server that
would populate this history table at a specified time each day.
• If we do this, the periodic data retrieval operation then has to read
data only from a single table that is heavily indexed, and the
operation would perform a lot faster.
Happy Coding 
• Visit www.programmerguide.net
• Like www.facebook.com/programmerguide
• Follow www.twitter.com/programmerguide
- Rajesh Gunasundaram

More Related Content

What's hot (20)

Data independence
Data independenceData independence
Data independence
Aashima Wadhwa
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
DataminingTools Inc
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
Aliya Saldanha
 
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache CalciteCost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
Julian Hyde
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
Joel Brewer
 
Stored procedure
Stored procedureStored procedure
Stored procedure
baabtra.com - No. 1 supplier of quality freshers
 
Query optimization
Query optimizationQuery optimization
Query optimization
dixitdavey
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
Ajeet Singh
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
Amrit Kaur
 
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentalsDB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
John Beresniewicz
 
SQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database PerformanceSQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database Performance
Mark Ginnebaugh
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
rehaniltifat
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
metsarin
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
Stamatis Zampetakis
 
Rdbms
RdbmsRdbms
Rdbms
rdbms
 
NOSQL Databases types and Uses
NOSQL Databases types and UsesNOSQL Databases types and Uses
NOSQL Databases types and Uses
Suvradeep Rudra
 
The Apache Spark File Format Ecosystem
The Apache Spark File Format EcosystemThe Apache Spark File Format Ecosystem
The Apache Spark File Format Ecosystem
Databricks
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
Douglas Bernardini
 
Datastage ppt
Datastage pptDatastage ppt
Datastage ppt
Newyorksys.com
 
MySQL Architecture and Engine
MySQL Architecture and EngineMySQL Architecture and Engine
MySQL Architecture and Engine
Abdul Manaf
 
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache CalciteCost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
Julian Hyde
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
Joel Brewer
 
Query optimization
Query optimizationQuery optimization
Query optimization
dixitdavey
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
Ajeet Singh
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
Amrit Kaur
 
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentalsDB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
John Beresniewicz
 
SQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database PerformanceSQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database Performance
Mark Ginnebaugh
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
rehaniltifat
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
metsarin
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
Stamatis Zampetakis
 
Rdbms
RdbmsRdbms
Rdbms
rdbms
 
NOSQL Databases types and Uses
NOSQL Databases types and UsesNOSQL Databases types and Uses
NOSQL Databases types and Uses
Suvradeep Rudra
 
The Apache Spark File Format Ecosystem
The Apache Spark File Format EcosystemThe Apache Spark File Format Ecosystem
The Apache Spark File Format Ecosystem
Databricks
 
MySQL Architecture and Engine
MySQL Architecture and EngineMySQL Architecture and Engine
MySQL Architecture and Engine
Abdul Manaf
 

Viewers also liked (19)

Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
nishantdavid9
 
New Database and Application Development Technology
New Database and Application Development TechnologyNew Database and Application Development Technology
New Database and Application Development Technology
Maurice Staal
 
Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2
Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2
Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2
Eddie Lycklama a Nijeholt
 
Verander legacy code in clean code!
Verander legacy code in clean code!Verander legacy code in clean code!
Verander legacy code in clean code!
David Baak
 
Business model canvas, NL, Dutch
Business model canvas, NL, DutchBusiness model canvas, NL, Dutch
Business model canvas, NL, Dutch
Onno Makor
 
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Nikolay Samokhvalov
 
My sql optimization
My sql optimizationMy sql optimization
My sql optimization
PrelovacMedia
 
Lean canvas model - NL
Lean canvas model - NLLean canvas model - NL
Lean canvas model - NL
What if Robert
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniques
guest54de52
 
Android & PostgreSQL
Android & PostgreSQLAndroid & PostgreSQL
Android & PostgreSQL
Mark Wong
 
Потоковая репликация PostgreSQL
Потоковая репликация PostgreSQLПотоковая репликация PostgreSQL
Потоковая репликация PostgreSQL
DevOWL Meetup
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practice
Jano Suchal
 
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Ontico
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
Brian Gallagher
 
Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестировании
ISsoft
 
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данныхОлег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данных
Siel01
 
как сделать свой кластер на postgresql 95
как сделать свой кластер на postgresql 95как сделать свой кластер на postgresql 95
как сделать свой кластер на postgresql 95
Максим Селиверстов
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
Karwin Software Solutions LLC
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
nishantdavid9
 
New Database and Application Development Technology
New Database and Application Development TechnologyNew Database and Application Development Technology
New Database and Application Development Technology
Maurice Staal
 
Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2
Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2
Paper - Meer balans in de IT vraag - Tias - Definitief - V2.2
Eddie Lycklama a Nijeholt
 
Verander legacy code in clean code!
Verander legacy code in clean code!Verander legacy code in clean code!
Verander legacy code in clean code!
David Baak
 
Business model canvas, NL, Dutch
Business model canvas, NL, DutchBusiness model canvas, NL, Dutch
Business model canvas, NL, Dutch
Onno Makor
 
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Nikolay Samokhvalov
 
Lean canvas model - NL
Lean canvas model - NLLean canvas model - NL
Lean canvas model - NL
What if Robert
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniques
guest54de52
 
Android & PostgreSQL
Android & PostgreSQLAndroid & PostgreSQL
Android & PostgreSQL
Mark Wong
 
Потоковая репликация PostgreSQL
Потоковая репликация PostgreSQLПотоковая репликация PostgreSQL
Потоковая репликация PostgreSQL
DevOWL Meetup
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practice
Jano Suchal
 
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Ontico
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
Brian Gallagher
 
Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестировании
ISsoft
 
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данныхОлег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данных
Siel01
 
как сделать свой кластер на postgresql 95
как сделать свой кластер на postgresql 95как сделать свой кластер на postgresql 95
как сделать свой кластер на postgresql 95
Максим Селиверстов
 
Ad

Similar to Query Optimization in SQL Server (20)

Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
Tips for Database Performance
Tips for Database PerformanceTips for Database Performance
Tips for Database Performance
Kesavan Munuswamy
 
dotnetMALAGA - Sql query tuning guidelines
dotnetMALAGA - Sql query tuning guidelinesdotnetMALAGA - Sql query tuning guidelines
dotnetMALAGA - Sql query tuning guidelines
Javier García Magna
 
Sql performance tuning
Sql performance tuningSql performance tuning
Sql performance tuning
Leo Mark Villar
 
SQL Server 2012 Best Practices
SQL Server 2012 Best PracticesSQL Server 2012 Best Practices
SQL Server 2012 Best Practices
Microsoft TechNet - Belgium and Luxembourg
 
A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 
A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 
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
uncleRhyme
 
Sql good practices
Sql good practicesSql good practices
Sql good practices
Deepak Mehtani
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL DatabasePerformance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
Tung Nguyen Thanh
 
presentation is on database for sql and stored procedures
presentation is on database for sql and stored procedurespresentation is on database for sql and stored procedures
presentation is on database for sql and stored procedures
harshsinghal08979
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008
paulguerin
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
ColdFusionConference
 
Ms sql server tips 1 0
Ms sql server tips 1 0Ms sql server tips 1 0
Ms sql server tips 1 0
Arman Nasrollahi
 
Indexing techniques
Indexing techniquesIndexing techniques
Indexing techniques
Huda Alameen
 
Database Performance
Database PerformanceDatabase Performance
Database Performance
Boris Hristov
 
Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005
rainynovember12
 
Sql server lesson6
Sql server lesson6Sql server lesson6
Sql server lesson6
Ala Qunaibi
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)
Ehtisham Ali
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
Kaing Menglieng
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
Tips for Database Performance
Tips for Database PerformanceTips for Database Performance
Tips for Database Performance
Kesavan Munuswamy
 
dotnetMALAGA - Sql query tuning guidelines
dotnetMALAGA - Sql query tuning guidelinesdotnetMALAGA - Sql query tuning guidelines
dotnetMALAGA - Sql query tuning guidelines
Javier García Magna
 
A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 
A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...A Review of Data Access Optimization Techniques in a Distributed Database Man...
A Review of Data Access Optimization Techniques in a Distributed Database Man...
Editor IJCATR
 
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
uncleRhyme
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL DatabasePerformance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
Tung Nguyen Thanh
 
presentation is on database for sql and stored procedures
presentation is on database for sql and stored procedurespresentation is on database for sql and stored procedures
presentation is on database for sql and stored procedures
harshsinghal08979
 
Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008Myth busters - performance tuning 102 2008
Myth busters - performance tuning 102 2008
paulguerin
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
ColdFusionConference
 
Indexing techniques
Indexing techniquesIndexing techniques
Indexing techniques
Huda Alameen
 
Database Performance
Database PerformanceDatabase Performance
Database Performance
Boris Hristov
 
Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005
rainynovember12
 
Sql server lesson6
Sql server lesson6Sql server lesson6
Sql server lesson6
Ala Qunaibi
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)
Ehtisham Ali
 
Ad

Recently uploaded (20)

14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfHow to purchase, license and subscribe to Microsoft Azure_PDF.pdf
How to purchase, license and subscribe to Microsoft Azure_PDF.pdf
victordsane
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 

Query Optimization in SQL Server

  • 1. Query Optimization • We develop and deploy web apps. It is much faster in development environment and in test server. However, the web app is subsequently degrading in performance. • When we investigating, we discovered that the production database was performing extremely slowly when the application was trying to access/update data. • Looking into the database, we find that the database tables have grown large in size and some of them were containing hundreds of thousands of rows. We found that the submission process was taking 5 long minutes to complete, whereas it used to take only 2/3 seconds to complete in the test server before production launch. • Here comes query optimization
  • 2. What is Indexing? • A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and storage space to maintain the index data structure. • Indexes are used to quickly locate data without having to search every row in a database table every time a database table is accessed. • Indexes can be created using one or more columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records.
  • 4. Cluster & Non-Cluster Index • Cluster Index will be created automatically when you add a Primary Key column in a table. Eg., ProductID • Only one cluster Index can be created for a table • Non-Cluster Index will be created to non-primary key columns • It is advisable to have maximum of 5 non-cluster index per table
  • 5. Non-Cluster Index should be created to Columns? • Frequently used in the search criteria • Used to join other tables • Used as foreign key fields • Of having high selectivity (column which returns a low percentage (0- 5%) of rows from a total number of rows on a particular value) • Used in the ORDER BY clause • Of type XML (primary and secondary indexes need to be created; more on this in the coming articles)
  • 6. Index Fragmentation • Index fragmentation is a situation where index pages split due to heavy insert, update, and delete operations on the tables in the database. If indexes have high fragmentation, either scanning/seeking the indexes takes much time, or the indexes are not used at all (resulting in table scan) while executing queries. Thus, data retrieval operations perform slow
  • 7. Types of Index Fragmentation • Internal Fragmentation: Occurs due to data deletion/update operations in the index pages which end up in the distribution of data as a sparse matrix in the index/data pages (creates lots of empty rows in the pages). Also results in an increase of index/data pages that increases query execution time. • External Fragmentation: Occurs due to data insert/update operations in the index/data pages which end up in page splitting and allocation of new index/data pages that are not contiguous in the file system. That reduces performance in determining the query result where ranges are specified in the "where" clauses.
  • 8. Defragmenting Indexes Reorganize indexes: execute the following command to do this: ALTER INDEX ALL ON TableName REORGANIZE Rebuild indexes: execute the following command to do this: ALTER INDEX ALL ON TableName REBUILD WITH (FILLFACTOR=90,ONLINE=ON) When to reorganize and when to rebuild indexes? • You should "reorganize" indexes when the External Fragmentation value for the corresponding index is between 10-15 and the Internal Fragmentation value is between 60-75. Otherwise, you should rebuild indexes.
  • 9. Move T-SQL from App to Database • We use ORM that generates all the SQL for us on the fly • Moving SQL from application and implementing them using Stored Procedures/Views/Functions/Triggers will enable you to eliminate any duplicate SQL in your application. This will also ensure re- usability of your TSQL codes. • Implementing all TSQL using database objects will enable you to analyse the TSQLs more easily to find possible inefficient codes that are responsible for the slow performance. Also, this will let you manage your TSQL codes from a central point. • Doing this will also enable you to re-factor your TSQL codes to take advantage of some advanced indexing techniques.
  • 10. Identify inefficient TSQL, re-factor, and apply best practices • Avoid unnecessary columns in the SELECT list and unnecessary tables in join conditions. • Do not use the COUNT() aggregate in a subquery to do an existence check • Avoid joining between two types of columns • TSQL using "Set based approach" rather than "Procedural approach“(use of Cursor or UDF to process rows in a result set) • Avoid dynamic SQL • Avoid the use of temporary tables • Implement a lazy loading strategy for large objects • Avoid the use of triggers • Use views for re-using complex TSQL blocks. Do not use views that retrieve data from a single table only
  • 11. Query Execution Plan • Whenever an SQL statement is issued in SQL Server engine, it first determines the best possible way to execute it. • The Query Optimizer (a system that generates the optimal query execution plan before executing the query) uses several information like the data distribution statistics, index structure, metadata, and other information to analyse several possible execution plans and finally select one that is likely to be the best execution plan most of the time. • We can use SQL Server Management Studio to preview and analyze the estimated execution plan for the query that you are going to issue
  • 13. Information Available on Query Execution Plan • Table Scan: Occurs when the corresponding table does not have a clustered index. Most likely, creating a clustered index or defragmenting index will enable you to get rid of it. • Clustered Index Scan: Sometimes considered equivalent to Table Scan. Takes place when a non-clustered index on an eligible column is not available. Most of the time, creating a non-clustered index will enable you to get rid of it. • Hash Join: The most expensive joining methodology. This takes place when the joining columns between two tables are not indexed. Creating indexes on those columns will enable you to get rid of it. • Nested Loops: Most cases, this happens when a non-clustered index does not include (Cover) a column that is used in the SELECT column list. In this case, for each member in the non-clustered index column, the database server has to seek into the clustered index to retrieve the other column value specified in the SELECT list. Creating a covered index will enable you to get rid of it. • RID Lookup: Takes place when you have a non-clustered index but the same table does not have any clustered index. In this case, the database engine has to look up the actual row using the row ID, which is an expensive operation. Creating a clustered index on the corresponding table would enable you to get rid of it.
  • 14. Steps in T-SQL Refactoring • Analysing the indexes • Analysing the query execution plan • Implementing some best practices • Implement computed columns and create indexes if necessary • Create Views and Indexed Views if Necessary
  • 15. Indexed Views • Views don't give you any significant performance benefit • Views are nothing but compiled queries, and Views just can't remember any result set • We can create indexed view so that it can remember the result set for the SELECT query it is composed of CREATE VIEW dbo.vOrderDetails WITH SCHEMABINDING AS SELECT...
  • 16. De-normalization • If you are designing a database for an OLTA system (Online Transaction Analytical system that is mainly a data warehouse which is optimized for read-only queries), you should apply heavy de- normalizing and indexing in your database. i.e., the same data will be stored across different tables, but the reporting and data analytical queries would run very faster. • If you are designing a database for an OLTP system (Online Transaction Processing System that is mainly a transactional system where mostly data update operations take place [that is, INSERT/UPDATE/DELETE]), implement at least 1st, 2nd, and 3rd Normal forms so that we can minimize data redundancy, and thus minimize data storage and increase manageability.
  • 17. History Tables • In an application, if we have some data retrieval operation (say, reporting) that periodically runs on a time period, and if the process involves tables that are large in size having normalized structure, we can consider moving data periodically from transactional normalized tables into a de-normalized, heavily indexed, single history table. • We can also create a scheduled operation in database server that would populate this history table at a specified time each day. • If we do this, the periodic data retrieval operation then has to read data only from a single table that is heavily indexed, and the operation would perform a lot faster.
  • 18. Happy Coding  • Visit www.programmerguide.net • Like www.facebook.com/programmerguide • Follow www.twitter.com/programmerguide - Rajesh Gunasundaram