Query Tuning Approach – For SQL Server and SQL Azure DB – Part2

It’s really important for a DBA to identify and tune the queries so that applications can perform at their best. If you are interested to learn the query tuning, you should at least have the understanding of the followings:

  1. Understand the phases of query processor/optimizer
  2. Purpose of query optimizer
  3. Indexing
  4. Statistics
  5. Types of execution plans (Estimated Vs Actual)
  6. Various execution plan operators like Index seek/scan, Joins, conversions , Compute scalar etc.
  7. Cardinality estimation
  8. Understand the purpose of data distribution in the table
  9. Various DMVs to understand the above information

Based on my experience, the query tuning world revolves around the above topics. If you manage to get a good understanding on the topics, you have already learnt why the query is performing slow. Rest all is an art which one learns with the experience.

We tried to cover these topics briefly during our SQL Server Delhi NCR community event as well. Though these topic were really big but we tried to share our experience on the field and information about must- knows on the above topics.

There are two approaches which we discussed in the event:
1. Proactive
2. Reactive

1. Proactive approach : This approach is really helpful to reduce the chances of major performance bottlenecks and help to understand the root cause of the ones , if occur. MDW is a great tool which really undervalued. I have personally implemented at many customers’ environments and it’s been really helpful to baseline the workload and identify the top bottlenecks and their causes. For more info on this, read this post
image

if we understand the system really well, we can identify the cause of the issues quickly. Generally, when the questions like ‘The application was working fine last month and suddenly performance started degrading’ arise we have no answers on what would have gone wrong. But if we have the performance baselining of good scenario , we can simply have a comparison the current state and identify the difference.

Moreover, optimal indexing plays a great role for the optimal performance. Many DBA’s tend to ignore this piece and work randomly on indexing when missing indexes warnings are seen in the execution plans. But as a proactive measure, if we can chuck out unused/duplicate indexes from the database – it really helps with optimal DDL and DML operations. This post is really helpful to find out such information from your server.

In my first post of this series, I have discussed on how to get the top resource intensive queries using query/plan hash. Once we have this information, we can simply start tuning the query after seeing the IO/Time statistics and execution plan of the query.

Reactive approach: This approach is generally followed when the issue is currently happening and we need to resolve the issue as quickly as possible. In this approach, we first try to find out the cause of contention which may be IO/CPU or memory. Once we identify the cause of contention, we need to pick up the queries accordingly.

image

If the cause of contention is CPU, steps mentioned in this post can be followed. If it’s memory/IO , we need to focus on high logical read queries and try to tune them. In my first post of this series, I have shared the queries to be used to identify the top logical read queries. Once we have those queries, we need to identify the IO/Time statistics along with their execution plans. As we know, all the DMV share the compile time plan and for run time execution plan , we need to run the query.

Once we have these statistics, my approach is as follows:

1. Look at the IO statistics and identify which table has the highest logical/physical reads
2. Look at the time statistics and see how long did it take to compile the query. Compile time may be high for the really big reporting queries.
3. Once the table with highest logical reads is identified – look at the execution plan with the highest cost in percentage which will mostly be around the operations on the same table.
4. Look and fix for the Index/table scan or key lookup in the execution plan
5. Look for the estimated and actual number of rows in the operators. If the actual rows are higher than the estimated rows – check the statistics of the table/columns
6. Look for the warnings in the plan for hash/sort/missing statistics or missing indexes

All the above mentioned steps will resolve 40-50% of the cases. Generally, indexing plays a vital role and fixing that itself will help to make the query run faster. When nothing of the above helps, then we need to go a bit deeper which is: Cardinality estimation which really depends on the data distribution of the table.

image

Majority of the query issues are caused by wrong cardinality estimation. Once we identify the issue with cardinality estimation, we need to dig and find out what could be the issue. Always try to calculate , how number of estimated rows were identified by query optimizer as there is a formula/reason behind every such calculation.

There are two really great videos from PASS 2014 which really talk about major execution plan issues and the cardinality estimation. If you go though them, you will understand the logic behind this discussion.

Cardinality Estimations:

Various Query Execution plan patterns:

This post covers the summary of Delhi NCR community December event session 2 – Learn SQL Query tuning

PPT can be found here. Demo Scripts can be found here.

Delhi NCR Community December event Session 1 – leverage Query Store for Query troubleshooting

On 19th December, we had completed the anniversary for the SQL Server Community for Delhi NCR. For this event, the agenda was as follows:

Session Title Speaker Contact Details
Leverage SQL 2016 Query Store for PTO Pranab Mazumdar Twitter , Blog
Tips for Query Tuning and Understand execution plan patterns Harsh Chawla Twitter , Blog
Tips of optimal Query Writing Sourabh Agarwal Twitter , Blog

In the first session, Pranab talked about query store a new feature for SQL 2016. The best , I could make out of the session was – now we can have run time plan captured in the tool for us. Before SQL 2014, we used to get compile time plan and to get the runtime plan, we had to run the query manually. Moreover, this feature can also be enabled on SQL Azure DBs as well.

Moreover, it’s really handy tool to enforce the best execution plan from all the execution plans already captured. Generally, we face issues after the upgrade to the newer versions i.e. our critical queries start taking longer time than than expected due to plan changes.If the backup of previous plan is not done, then it’s difficult to restore the execution time back to as normal.

Now, we can enable this tool on the test environment and replay the load of production system. It can help to capture the execution plans efficiently and help to pick up the efficient plan if there is any performance degradation on the upgraded SQL instance due to the new execution plan.
PPT and demo scripts are attached with this post – please feel free to download and try it on SQL server 2016 instances.

HTH!

Query Tuning Approach – For SQL Server and SQL Azure DB – Part1

It’s been really long since I have written a post. I have been working on lots of query tuning my in recent past and I thought of sharing my approach.I have been using this approach for quite some time now and have got really good success rate to tune the query.

Just understand one rule, 80% of the times you will encounter queries which can be tuned by intermediate skills. It’ll be just 20% or even lesser when you will need some extreme level of query tuning skills. Honestly speaking, I rarely get into such situations where I see the query is complex to be tuned – really rare. I have been using really basic approach to combat bad queries and it’s really serving well for my customers.

I assume , you know how to identify which queries should be picked up for tuning e.g. if you are facing high CPU issues , you need to pick CPU intensive queries or if you are facing memory pressure or slow I/O , you need you pick high logical/physical read queries. Now, you know the resource contention on your system – let’s see what to do next:

1. Query to get top resource intensive queries: I have picked these queries from the PSSDIAG tool mentioned here

print ‘– top 10 CPU by query_hash –‘

select getdate() as runtime, *
from
(
SELECT TOP 10 query_hash, COUNT (distinct query_plan_hash) as ‘distinct query_plan_hash count’,
sum(execution_count) as ‘execution_count’,
sum(total_worker_time) as ‘total_worker_time’,
SUM(total_elapsed_time) as ‘total_elapsed_time’,
SUM (total_logical_reads) as ‘total_logical_reads’,
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 – qs.statement_start_offset/2 + 1
END), CHAR(13), ‘ ‘), CHAR(10), ‘ ‘))  AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_hash
ORDER BY sum(total_worker_time) DESC
) t

print ‘– top 10 logical reads by query_hash –‘

select getdate() as runtime, *
from
(
SELECT TOP 10 query_hash,
COUNT (distinct query_plan_hash) as ‘distinct query_plan_hash count’,
sum(execution_count) as ‘execution_count’,
sum(total_worker_time) as ‘total_worker_time’,
SUM(total_elapsed_time) as ‘total_elapsed_time’,
SUM (total_logical_reads) as ‘total_logical_reads’,
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 – qs.statement_start_offset/2 + 1
END), CHAR(13), ‘ ‘), CHAR(10), ‘ ‘))  AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_hash
ORDER BY sum(total_logical_reads) DESC
) t

print ‘– top 10 elapsed time by query_hash –‘

select getdate() as runtime, *
from
(
SELECT TOP 10 query_hash,
sum(execution_count) as ‘execution_count’,
COUNT (distinct query_plan_hash) as ‘distinct query_plan_hash count’,
sum(total_worker_time) as ‘total_worker_time’,
SUM(total_elapsed_time) as ‘total_elapsed_time’,
SUM (total_logical_reads) as ‘total_logical_reads’,
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 – qs.statement_start_offset/2 + 1
END), CHAR(13), ‘ ‘), CHAR(10), ‘ ‘))  AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_hash
ORDER BY sum(total_elapsed_time) DESC
) t

print ‘– top 10 CPU by query_plan_hash and query_hash –‘

SELECT TOP 10 query_plan_hash, query_hash,
COUNT (distinct query_plan_hash) as ‘distinct query_plan_hash count’,
sum(execution_count) as ‘execution_count’,
sum(total_worker_time) as ‘total_worker_time’,
SUM(total_elapsed_time) as ‘total_elapsed_time’,
SUM (total_logical_reads) as ‘total_logical_reads’,
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 – qs.statement_start_offset/2 + 1
END), CHAR(13), ‘ ‘), CHAR(10), ‘ ‘))  AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_plan_hash, query_hash
ORDER BY sum(total_worker_time) DESC;

print ‘– top 10 logical reads by query_plan_hash and query_hash –‘

SELECT TOP 10 query_plan_hash, query_hash, sum(execution_count) as ‘execution_count’,
sum(total_worker_time) as ‘total_worker_time’,
SUM(total_elapsed_time) as ‘total_elapsed_time’,
SUM (total_logical_reads) as ‘total_logical_reads’,
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 – qs.statement_start_offset/2 + 1
END), CHAR(13), ‘ ‘), CHAR(10), ‘ ‘))  AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_plan_hash, query_hash
ORDER BY sum(total_logical_reads) DESC;

print ‘– top 10 elapsed time  by query_plan_hash and query_hash –‘

SELECT TOP 10 query_plan_hash, query_hash, sum(execution_count) as ‘execution_count’,
sum(total_worker_time) as ‘total_worker_time’,
SUM(total_elapsed_time) as ‘total_elapsed_time’,
SUM (total_logical_reads) as ‘total_logical_reads’,
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 – qs.statement_start_offset/2 + 1
END), CHAR(13), ‘ ‘), CHAR(10), ‘ ‘))  AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_plan_hash, query_hash
ORDER BY sum(total_elapsed_time) DESC;

2. Check the execution plan for the query – Just remember , wherever you get the top resource intensive queries – be it MDW / Profiler / DMVs – you will get an option to get SQL Handle / Plan Handle/ SQL Hash / Plan Hash. If you have any of these , you can get an execution plan from the cache.

Query to get the execution plan is:

This will give you the query execution and plan

select b.*,a.* from sys.dm_exec_query_stats a cross apply
sys.dm_exec_query_plan  (a.plan_handle) b
where a.query_hash= <Query_hash>

if you want to know , execution statistics specific to the plan e.g. how many times the plan was reused – in the above output , you will get:

image

There can be multiple plans as well but you need to pick up the plans with More reads/CPU/time based on execution count.

3. Get the query parameters for the runtime planJust remember , the plans you get from these DMVs are the compile time plans and to get the actual plans – you will need to run the query on your SQL Instance. I have observed, DBAs ask the developer team to share the parameters of the query so that, they can run the query  on the test environment. In fact, if you have the query plan – you can get the parameter from there itself. let’s how to get that:

Right click on the graphical execution plan and click on show execution plan as XML – once the xml plan is visible , search for ParameterList as show below:

image

4. Execute the query :  Now, it’s the time to execute the query and analyze the actual statistics. leverage the below commands to delve deeper into the query execution:

Set statistics IO ON –>   Get the IO statistics of the query

Table ‘residual_demo’. Scan count 1, logical reads 3, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Set statistics Time ON –> Get the time statistics of the query i.e. how long it took for the query for compilation and running

SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.

SQL Server Execution Times:
CPU time = 0 ms,  elapsed time = 0 ms.

Set Statistics Profile ON –> Get the execution plan of the query in the text format
image

or
get the graphical execution by clicking on the actual execution plan from the Management Studio

Depending on the issue you are troubleshooting, the operator to be analyzed will vary. e.g. If you are tuning query for CPU intensive workload then probably the first thing to look at will be sort and for high logical reads , it will be an index/table scans

In this post, we have got the execution plan and now we have to start the tuning process. In the next post, I will talk about the operators you can pick for the tuning.

HTH!

SQL UG meet Delhi NCR – Theme – Performance and Tuning of SQL Server

This event was held on 19th September, where we had DB professionals coming from all over Delhi NCR region. Agenda of this event was :
1. SQL Performance Troubleshooting using PSSDIAG and SQLNexus
2. Reduce downtime on Production Server – How to Manage SQL Server Proactively
3. Increase IOPS to handle SQL workloads using Windows 2012 storage spaces

SQL Performance Troubleshooting using PSSDIAG and SQLNexus : This session was delivered by Amit Khandelwal , Support Escalation Engineer , India GTSC. He explained about
1. PSSDIAG configuration and SQL Nexus in detail.
2. Helped the audience understand , the use of this tool while troubleshooting performance issues.
3. Explained about IO issues and tips to troubleshoot such issues
4. Shared some trace flags which can be enabled on all the SQL environments as best practices
5. Shared some tricks while troubleshooting the SQL performance before delving deeper.

Session PPT can be found here

Reduce downtime on Production Server – How to Manage SQL Server Proactively : This sessions was delivered by Harsh Chawla , Premier Field Engineer , Microsoft Services(myself) on how to be more proactive while working on the production server. This was a philosophical session on how as a DBA can change his mindset while working on the database and be more efficient on the job. In this presentation , the complete discussion was around a production down scenario and how it could be avoided. There were a major discussion around , these three rules:

1. Understand your “Present” – Just be aware of the Application, business purpose/impact, SLA/RPO/RTO and hardware configuration of SQL Server you are working on.
2. Invest for better “Future” – Follow the right practices and have the correct configuration in place to avoid any issues in future.
3. Don’t Ignore “Past” – Have right monitoring and auditing solution to track the cause of the issues in the past.

Session PPT can be found here

Increase IOPS to handle SQL workloads using Windows 2012 storage spaces :  This session was delivered by Gaurav Srivastava , Service Engineer , Microsoft IT. He talked about how storage spaces can help you with high disk performance even without using SANs. Storage spaces is the feature from Windows 2012 and is very useful when you deploy SQL on Azure VMs. Nevertheless , the same feature can be used even for on-premise SQL server deployed on Windows 2012. He talked about:
1. Storage Pools
2. Disk caching
3. Storage spaces types – Simple, Mirror and Parity
4. Tools like Diskpd and SQLIO to see the disk IOPS and latency
5. Shared the demo of creating Storage pools and spaces using Powershell and GUI

Session PPT and Scripts can be found here

Disclaimer – The views expressed on this website/blog are mine alone and do not reflect the views of my company. All postings on this blog are provided “AS IS” with no warranties, and confers no rights.

HTH!

List of SQL server readiness links for Self learning!

I have been interacting with DBAs consultants as part of my work for a long time now. I have been getting a common request on SQL learning resources and mostly for a collated list of blogs / learning materials for self-study. I thought of writing this post where I could mention the resources , you can simply add to your browser favorites and refer at leisure. If you are new or enhancing your skills on SQL server, this information will help you grow further.

In this post you will see :

1. List of Microsoft SQL server teams’ Blog websites
2. SQL learning free video library
3. List of SQL fundamental and troubleshooting learning
4. Report SQL server bugs website
5. Sites to download SQL Troubleshooting tools
6. List of Facebook Pages/groups for help and getting latest community events updates

Microsoft Team Blogs:
These blogs are managed by Microsoft teams directly and can be referred for the latest updates and SQL features.

SQL Customer Advisory Team blog – http://blogs.msdn.com/b/sqlcat/
SQL server CSS SQL server Engineer’s blog – http://blogs.msdn.com/b/psssql/
SQL server PFE blog – http://blogs.msdn.com/b/sql_pfe_blog/
Microsoft GTSC – SQL server troubleshooting blog – http://blogs.msdn.com/b/sqlserverfaq/
Microsoft SQL server Team Blog – http://blogs.technet.com/b/dataplatforminsider/

SQL Video Libraries:
You can view/download free videos from these websites for your SQL server learning –

Free videos for SQL learning – https://www.sqlskills.com/sql-server-resources/sql-server-mcm-training-videos/
Free Videos from Microsoft Team – https://channel9.msdn.com/
Free Videos from Microsoft GTSC Team – http://blogs.msdn.com/b/sqlserverfaq/archive/tags/dbvideo/

SQL Learning/troubleshooting blog :
These links can be referred for the SQL fundamental and troubleshooting learning.

SQL fundamentals and features blog – http://sqlblog.com/
SQL Skills – https://www.sqlskills.com/sql-server-resources/
Query Processing and Optimization – http://blogs.msdn.com/b/sqlqueryprocessing/
Bart Duncan’s Query Processing and Optimization Blog –http://blogs.msdn.com/b/bartd/
Craig Freedman’s Query Processing and Optimization Blog- http://blogs.msdn.com/b/craigfr/
Microsoft SQL server Library – https://msdn.microsoft.com/en-us/library/bb545450.aspx
SQL Authority Blog – http://blog.sqlauthority.com/author/pinaldave/
SQL/.net blog – http://blogs.msdn.com/b/arvindsh/
SQL PTO Blog – http://www.brentozar.com/blog/
SQL AlwaysON blog –http://blogs.msdn.com/b/sqlalwayson/
SQL troubleshooting blog – http://troubleshootingsql.com/
SQL & BI blog – http://www.sqlserverfaq.net/
SQL PTO blog – http://blogs.msdn.com/b/blogdoezequiel/
SQL AlwaysON and SQL 2014 learning blog – http://sqlserver-help.com/
SQL learning blog – http://sqluninterrupted.com/
SQL /Azure learning  – http://dbcouncil.net
SQL troubleshooting blog – http://mssqlwiki.com/
SQL Learning Blog – http://www.sqlservergeeks.com/

 

Report Bug for SQL server :
If you suspect you have hit a bug with SQL server, you can notify or vote for the bug on this forum –
Microsoft Connect website – http://connect.microsoft.com/

SQL Forums:
If you are stuck on SQL server issues, you can post your questions in these forums to get help –

Microsoft’s SQL server Forum – https://social.msdn.microsoft.com/Forums/en-US/home
Microsoft’s SQL server Forum – https://social.technet.microsoft.com/Forums/sqlserver/en-US/home
SQL server Central – http://www.sqlservercentral.com/Forums/
SQL Team Blog –http://www.sqlteam.com/forums/

SQL Facebook pages/groups:
If you want to join SQL community events for free in your region, you can join these groups for the further updates. Moreover, you can also put your questions in these groups:

SQL Server Delhi NCR community –https://www.facebook.com/groups/1537669073140700/
SQLserverFAQ – https://www.facebook.com/groups/213527572040350/
SQL Bangalore Group –https://www.facebook.com/groups/SQLBangalore/
SQL Server DBA group – https://www.facebook.com/groups/sqlserverdbaindia/
MSSQLWIKI – https://www.facebook.com/groups/mssqlwiki/
Mumbai Techie Group – https://www.facebook.com/MumbaiTechieGroup?fref=ts

Troubleshooting tools site:
This can be used to get latest troubleshooting tools.
Sysinternals – https://technet.microsoft.com/en-us/sysinternals
Codeplex – http://www.codeplex.com/

The list is huge but I have tried to keep as optimal as possible to make this relevant for you. However, I will keep on updating more links for you.

HTH!