SlideShare une entreprise Scribd logo
1  sur  18
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

Contenu connexe

Tendances

12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architectureAmrit Kaur
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexingMahabubur Rahaman
 
Designing and Building Next Generation Data Pipelines at Scale with Structure...
Designing and Building Next Generation Data Pipelines at Scale with Structure...Designing and Building Next Generation Data Pipelines at Scale with Structure...
Designing and Building Next Generation Data Pipelines at Scale with Structure...Databricks
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architectureAjeet Singh
 
Oracle Table Partitioning - Introduction
Oracle Table Partitioning  - IntroductionOracle Table Partitioning  - Introduction
Oracle Table Partitioning - IntroductionMyOnlineITCourses
 
BigTable And Hbase
BigTable And HbaseBigTable And Hbase
BigTable And HbaseEdward Yoon
 
Informatica Online Training
Informatica Online Training Informatica Online Training
Informatica Online Training saikirancrs
 
ETL in the Cloud With Microsoft Azure
ETL in the Cloud With Microsoft AzureETL in the Cloud With Microsoft Azure
ETL in the Cloud With Microsoft AzureMark Kromer
 
Always on in sql server 2017
Always on in sql server 2017Always on in sql server 2017
Always on in sql server 2017Gianluca Hotz
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuningGuy Harrison
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuningSimon Huang
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to CassandraGokhan Atil
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Aaron Shilo
 
Part1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the OptimizerPart1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the OptimizerMaria Colgan
 

Tendances (20)

12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architecture
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
SQL
SQLSQL
SQL
 
Designing and Building Next Generation Data Pipelines at Scale with Structure...
Designing and Building Next Generation Data Pipelines at Scale with Structure...Designing and Building Next Generation Data Pipelines at Scale with Structure...
Designing and Building Next Generation Data Pipelines at Scale with Structure...
 
NoSql
NoSqlNoSql
NoSql
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 
Oracle Table Partitioning - Introduction
Oracle Table Partitioning  - IntroductionOracle Table Partitioning  - Introduction
Oracle Table Partitioning - Introduction
 
BigTable And Hbase
BigTable And HbaseBigTable And Hbase
BigTable And Hbase
 
Informatica Online Training
Informatica Online Training Informatica Online Training
Informatica Online Training
 
ETL in the Cloud With Microsoft Azure
ETL in the Cloud With Microsoft AzureETL in the Cloud With Microsoft Azure
ETL in the Cloud With Microsoft Azure
 
Always on in sql server 2017
Always on in sql server 2017Always on in sql server 2017
Always on in sql server 2017
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuning
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
Introduction to Cassandra
Introduction to CassandraIntroduction to Cassandra
Introduction to Cassandra
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
 
Key-Value NoSQL Database
Key-Value NoSQL DatabaseKey-Value NoSQL Database
Key-Value NoSQL Database
 
Part1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the OptimizerPart1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the Optimizer
 
Unit 4 plsql
Unit 4  plsqlUnit 4  plsql
Unit 4 plsql
 

En vedette

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 sqlnishantdavid9
 
New Database and Application Development Technology
New Database and Application Development TechnologyNew Database and Application Development Technology
New Database and Application Development TechnologyMaurice 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.2Eddie 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, DutchOnno 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 - NLWhat if Robert
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniquesguest54de52
 
Android & PostgreSQL
Android & PostgreSQLAndroid & PostgreSQL
Android & PostgreSQLMark Wong
 
Потоковая репликация PostgreSQL
Потоковая репликация PostgreSQLПотоковая репликация PostgreSQL
Потоковая репликация PostgreSQLDevOWL Meetup
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practiceJano Suchal
 
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский Ontico
 
Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестированииISsoft
 
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данныхОлег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данныхSiel01
 
как сделать свой кластер на postgresql 95
как сделать свой кластер на postgresql 95как сделать свой кластер на postgresql 95
как сделать свой кластер на postgresql 95Максим Селиверстов
 

En vedette (18)

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
 
New Database and Application Development Technology
New Database and Application Development TechnologyNew Database and Application Development Technology
New Database and Application Development Technology
 
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
 
Verander legacy code in clean code!
Verander legacy code in clean code!Verander legacy code in clean code!
Verander legacy code in clean code!
 
Business model canvas, NL, Dutch
Business model canvas, NL, DutchBusiness model canvas, NL, Dutch
Business model canvas, NL, Dutch
 
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
 
My sql optimization
My sql optimizationMy sql optimization
My sql optimization
 
Lean canvas model - NL
Lean canvas model - NLLean canvas model - NL
Lean canvas model - NL
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniques
 
Android & PostgreSQL
Android & PostgreSQLAndroid & PostgreSQL
Android & PostgreSQL
 
Потоковая репликация PostgreSQL
Потоковая репликация PostgreSQLПотоковая репликация PostgreSQL
Потоковая репликация PostgreSQL
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
SQL: Query optimization in practice
SQL: Query optimization in practiceSQL: Query optimization in practice
SQL: Query optimization in practice
 
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
Испытание поединком PostgreSQL vs MySQL / Александр Чистяков, Даниил Подольский
 
Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестировании
 
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данныхОлег Царев, Кирилл Коринский   Сравнительный анализ хранилищ данных
Олег Царев, Кирилл Коринский Сравнительный анализ хранилищ данных
 
как сделать свой кластер на 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
 

Similaire à Query Optimization in SQL Server

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
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server DatabasesColdFusionConference
 
MySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMahesh Salaria
 
Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005rainynovember12
 
Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…Aaron Shilo
 
AWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationAWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationVolodymyr Rovetskiy
 
Optimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxOptimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxJasonTuran2
 
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
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Web Services
 
Tips for Database Performance
Tips for Database PerformanceTips for Database Performance
Tips for Database PerformanceKesavan Munuswamy
 
How to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftHow to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftAWS Germany
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09guest9d79e073
 
Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Brad McGehee Intepreting Execution Plans Mar09
Brad McGehee Intepreting Execution Plans Mar09Mark Ginnebaugh
 
MySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMahesh Salaria
 

Similaire à Query Optimization in SQL Server (20)

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
 
Sql performance tuning
Sql performance tuningSql performance tuning
Sql performance tuning
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
 
MySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMySQL: Know more about open Source Database
MySQL: Know more about open Source Database
 
Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005
 
Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…
 
AWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentationAWS (Amazon Redshift) presentation
AWS (Amazon Redshift) presentation
 
Optimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxOptimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptx
 
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...
 
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...
 
Data warehouse physical design
Data warehouse physical designData warehouse physical design
Data warehouse physical design
 
Amazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and OptimizationAmazon Redshift: Performance Tuning and Optimization
Amazon Redshift: Performance Tuning and Optimization
 
Breaking data
Breaking dataBreaking data
Breaking data
 
Tips for Database Performance
Tips for Database PerformanceTips for Database Performance
Tips for Database Performance
 
People soft basics
People soft basicsPeople soft basics
People soft basics
 
How to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon RedshiftHow to Fine-Tune Performance Using Amazon Redshift
How to Fine-Tune Performance Using Amazon Redshift
 
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
 
Tunning overview
Tunning overviewTunning overview
Tunning overview
 
MySQL: Know more about open Source Database
MySQL: Know more about open Source DatabaseMySQL: Know more about open Source Database
MySQL: Know more about open Source Database
 

Dernier

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 

Dernier (20)

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 

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