<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/clustering-executed-sql-server-queries-using-r-as-tool-for/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://tomaztsql.wordpress.com/2017/01/08/clustering-executed-sql-server-queries-using-r-as-tool-for/"> R – TomazTsql</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>When query execution performance analysis is to be done, there are many ways to find which queries might cause any unwanted load or cause stall on the server.</p>
<p>By encouraging DBA community to start practicing the advantage or R Language and world of data science, I have created a demo to show, how statistics on numerous queries can be stored for later analysis. And this demo has unsupervised (or undirected) method for grouping similar query statistics (or queries) to easier track and find where and which queries might be potential system stoppers.</p>
<p>Before we run some queries to generate the running statistics for these queries, we clean the cache and prepare the table for storing statistics from sys.dm_exec_query_stats.</p>
<pre>-- drop statistics table
DROP TABLE IF EXISTS  query_stats_LOG_2;
DROP PROCEDURE IF EXISTS AbtQry;
DROP PROCEDURE IF EXISTS SalQry;
DROP PROCEDURE IF EXISTS PrsQry;
DROP PROCEDURE IF EXISTS OrdQry;
DROP PROCEDURE IF EXISTS PurQry;
GO

-- Clean all the stuff only for the selected db
DECLARE @dbid INTEGER
SELECT @dbid = [dbid] 
FROM master..sysdatabases 
WHERE name = 'WideWorldImportersDW'
DBCC FLUSHPROCINDB (@dbid);
GO

-- for better sample, check that you have Query store turned off
ALTER DATABASE WideWorldImportersDW SET  QUERY_STORE = OFF;
GO</pre>
<p>We generate some fake data:</p>
<pre>USE WideWorldImportersDW;
GO

-- CREATE Procedures 

CREATE PROCEDURE AbtQry
(@AMNT AS INTEGER) 
AS

-- an arbitrary query
SELECT 
  cu.[Customer Key] AS CustomerKey
  ,cu.Customer
  ,ci.[City Key] AS CityKey
  ,ci.City
  ,ci.[State Province] AS StateProvince
  ,ci.[Sales Territory] AS SalesTeritory
  ,d.Date
  ,d.[Calendar Month Label] AS CalendarMonth
  ,s.[Stock Item Key] AS StockItemKey
  ,s.[Stock Item] AS Product
  ,s.Color
  ,e.[Employee Key] AS EmployeeKey
  ,e.Employee
  ,f.Quantity
  ,f.[Total Excluding Tax] AS TotalAmount
  ,f.Profit
 
FROM Fact.Sale AS f
  INNER JOIN Dimension.Customer AS cu
    ON f.[Customer Key] = cu.[Customer Key]
  INNER JOIN Dimension.City AS ci
    ON f.[City Key] = ci.[City Key]
  INNER JOIN Dimension.[Stock Item] AS s
    ON f.[Stock Item Key] = s.[Stock Item Key]
  INNER JOIN Dimension.Employee AS e
    ON f.[Salesperson Key] = e.[Employee Key]
  INNER JOIN Dimension.Date AS d
    ON f.[Delivery Date Key] = d.Date
WHERE
    f.[Total Excluding Tax] BETWEEN 10 AND @AMNT;
GO

CREATE PROCEDURE SalQry
(@Q1 AS INTEGER
,@Q2 AS INTEGER)

AS
-- FactSales Query
SELECT * FROM Fact.Sale
WHERE
    Quantity BETWEEN @Q1 AND @Q2;
GO

CREATE PROCEDURE PrsQry
(@CID AS INTEGER )
AS

-- Person Query
SELECT * 
    FROM [Dimension].[Customer]
    WHERE [Buying Group] &lt;> 'Tailspin Toys' 
    /* OR [WWI Customer ID] > 500 */
    AND [WWI Customer ID] BETWEEN 400 AND  @CID
ORDER BY [Customer],[Bill To Customer];
GO


CREATE PROCEDURE OrdQry
(@CK AS INTEGER)
AS

-- FactSales Query
SELECT 
    * 
    FROM [Fact].[Order] AS o
    INNER JOIN [Fact].[Purchase] AS p 
    ON o.[Order Key] = p.[WWI Purchase Order ID]
WHERE
    o.[Customer Key] = @CK;
GO

CREATE PROCEDURE PurQry
(@Date AS SMALLDATETIME)
AS

-- FactPurchase Query
SELECT *
    FROM [Fact].[Purchase]
        WHERE
        [Date Key] = @Date;
    --[Date KEy] = '2015/01/01'
GO</pre>
<p>Now we run procedures couple of times:</p>
<pre>DECLARE @ra DECIMAL(10,2)
SET @ra = RAND()
SELECT CAST(@ra*10 AS INT)

IF @ra  &lt; 0.3333
    BEGIN
       -- SELECT 'RAND &lt; 0.333', @ra
       DECLARE @AMNT_i1 INT = 100*CAST(@ra*10 AS INT)
       EXECUTE AbtQry @AMNT = @AMNT_i1
       EXECUTE PurQry @DAte = '2015/10/01'
       EXECUTE PrsQry @CID = 480
       EXECUTE OrdQry @CK = 0
       DECLARE @Q1_i1 INT = 1*CAST(@ra*10 AS INT)
       DECLARE @Q2_i1 INT = 20*CAST(@ra*10 AS INT)
       EXECUTE SalQry @Q1 = @Q1_i1, @Q2 = @Q2_i1

    END
ELSE 
    IF @ra  > 0.3333 AND @ra &lt; 0.6667
    BEGIN
        -- SELECT 'RAND > 0.333 | &lt; 0.6667', @ra
        DECLARE @AMNT_i2 INT = 500*CAST(@ra*10 AS INT)
        EXECUTE AbtQry @AMNT = @AMNT_i2
        EXECUTE PurQry @DAte = '2016/04/29'
        EXECUTE PrsQry @CID = 500
        EXECUTE OrdQry @CK = 207
        DECLARE @Q1_i2 INT = 2*CAST(@ra*10 AS INT)
        DECLARE @Q2_i2 INT = 10*CAST(@ra*10 AS INT)
        EXECUTE SalQry @Q1 = @Q1_i2, @Q2 = @Q2_i2

    END
ELSE
    BEGIN
        -- SELECT 'RAND > 0.6667', @ra
        DECLARE @AMNT_i3 INT = 800*CAST(@ra*10 AS INT)
        EXECUTE AbtQry @AMNT = @AMNT_i3
        EXECUTE PurQry @DAte = '2015/08/13'
        EXECUTE PrsQry @CID = 520
        EXECUTE OrdQry @CK = 5
        DECLARE @Q2_i3 INT = 60*CAST(@ra*10 AS INT)
        EXECUTE SalQry @Q1 = 25, @Q2 = @Q2_i3
    END
GO 10</pre>
<p>And with this data, we proceed to run the logging T-SQL (query <a target="_blank" rel="nofollow" href="https://msdn.microsoft.com/en-us/library/ms189741.aspx">source</a>).</p>
<pre>SELECT
    (total_logical_reads + total_logical_writes) AS total_logical_io
    ,(total_logical_reads / execution_count) AS avg_logical_reads
    ,(total_logical_writes / execution_count) AS avg_logical_writes
    ,(total_physical_reads / execution_count) AS avg_phys_reads
    ,substring(st.text,(qs.statement_start_offset / 2) + 1,  
      ((CASE qs.statement_end_offset WHEN - 1 THEN datalength(st.text) 
   qs.statement_end_offset END  - qs.statement_start_offset) / 2) + 1) 
AS statement_text
    ,*
INTO query_stats_LOG_2
FROM
        sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY total_logical_io DESC</pre>
<p>Now that we have gathered some test data, we can proceed to do clustering analysis.</p>
<p>Since I don’t know how many clusters can there be, and I can imagine, a  DBA would also be pretty much clueless, I will explore number of clusters. Following R code:</p>
<pre>library(RODBC)
myconn &lt;-odbcDriverConnect(&quot;driver={SQL Server};Server=SICN-KASTRUN;
database=WideWorldImportersDW;trusted_connection=true&quot;)

query.data &lt;- sqlQuery(myconn, &quot;
                     SELECT 
                                 [total_logical_io]
                      ,[avg_logical_reads]
                      ,[avg_phys_reads]
                      ,execution_count
                      ,[total_physical_reads]
                      ,[total_elapsed_time]
                      ,total_dop
                      ,
                      ,CASE WHEN LEFT(,70) LIKE '%AbtQry%' THEN 'AbtQry'
                       WHEN LEFT(,70) LIKE '%OrdQry%' THEN 'OrdQry'
                       WHEN LEFT(,70) LIKE '%PrsQry%' THEN 'PrsQry'
                       WHEN LEFT(,70) LIKE '%SalQry%' THEN 'SalQry'
                       WHEN LEFT(,70) LIKE '%PurQry%' THEN 'PurQry'
                       HEN LEFT(,70) LIKE '%@BatchID%' THEN 'System'
                                  ELSE 'Others' END AS label_graph 
                      FROM query_stats_LOG_2&quot;)

close(myconn) 
library(cluster)

#qd &lt;- query.data[,c(1,2,3,5,6)]
qd &lt;- query.data[,c(1,2,6)]

## hierarchical clustering
qd.use &lt;- query.data[,c(1,2,6)]
medians &lt;- apply(qd.use,2,median)
#mads &lt;- apply(qd.use,2,mad)
qd.use &lt;- scale(qd.use,center=medians) #,scale=mads)

#calculate distances
query.dist &lt;- dist(qd.use)

# hierarchical clustering
query.hclust &lt;- hclust(query.dist)

# plotting solution
op &lt;- par(bg = &quot;lightblue&quot;)
plot(query.hclust,labels=query.data$label_graph,
main='Query Hierarchical Clustering', ylab = 'Distance', 
xlab = ' ', hang = -1, sub = &quot;&quot; )
# in addition to circle queries within cluster
rect.hclust(query.hclust, k=3, border=&quot;DarkRed&quot;)        
</pre>
<p>And produces the following plot:</p>
<p><img sizes="(max-width: 621px) 100vw, 621px" data-image-description="" data-orig-file="https://i0.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_05-plot-zoom.png?w=456&amp;ssl=1" data-orig-size="621,397" data-image-title="2017-01-08-10_46_05-plot-zoom" class="wp-image-3263" data-comments-opened="1" data-recalc-dims="1" data-attachment-id="3263" data-permalink="https://tomaztsql.wordpress.com/2017/01/08/clustering-executed-sql-server-queries-using-r-as-tool-for/2017-01-08-10_46_05-plot-zoom/#main" alt="2017-01-08-10_46_05-plot-zoom" data-medium-file="https://i0.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_05-plot-zoom.png?w=456&amp;ssl=1?w=300" data-large-file="https://i0.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_05-plot-zoom.png?w=456&amp;ssl=1?w=621" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i0.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_05-plot-zoom.png?w=456&ssl=1"></p>
<p>Graph itself is self explanatory and based on the gathered statistics and queries executed against the system, you receive the groups of queries where your DBA can easily and fast track down what might be causing some issues. I added some labels to the query for the graph to look neater, but it is up to you.</p>
<p>I have also changed the type to “triangle” to get the following plot:</p>
<p><img sizes="(max-width: 590px) 100vw, 590px" data-image-description="" data-orig-file="https://i2.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_54_55-plot-zoom.png?w=456&amp;ssl=1" data-orig-size="590,394" data-image-title="2017-01-08-10_54_55-plot-zoom" data-comments-opened="1" class="wp-image-3269" data-recalc-dims="1" data-attachment-id="3269" data-permalink="https://tomaztsql.wordpress.com/2017/01/08/clustering-executed-sql-server-queries-using-r-as-tool-for/2017-01-08-10_54_55-plot-zoom/#main" alt="2017-01-08-10_54_55-plot-zoom" data-medium-file="https://i2.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_54_55-plot-zoom.png?w=456&amp;ssl=1?w=300" data-large-file="https://i2.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_54_55-plot-zoom.png?w=456&amp;ssl=1?w=590" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i2.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_54_55-plot-zoom.png?w=456&ssl=1"></p>
<p>And both show same information.</p>
<p>So the R code said that, there are three clusters generating And I used medians to generate data around it. In addition I have also tested the result with Partitioning around medoids (which is opposite to hierarchical clustering) and the results from both techniques yield clean clusters.</p>
<p><img sizes="(max-width: 323px) 100vw, 323px" data-image-description="" data-orig-file="https://i1.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_47-rstudio.png?w=456&amp;ssl=1" data-orig-size="323,92" data-image-title="2017-01-08-10_46_47-rstudio" data-comments-opened="1" class="wp-image-3275" data-recalc-dims="1" data-attachment-id="3275" data-permalink="https://tomaztsql.wordpress.com/2017/01/08/clustering-executed-sql-server-queries-using-r-as-tool-for/2017-01-08-10_46_47-rstudio/#main" alt="2017-01-08-10_46_47-rstudio" data-medium-file="https://i1.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_47-rstudio.png?w=456&amp;ssl=1?w=300" data-large-file="https://i1.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_47-rstudio.png?w=456&amp;ssl=1?w=323" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i1.wp.com/tomaztsql.files.wordpress.com/2017/01/2017-01-08-10_46_47-rstudio.png?w=456&ssl=1"></p>
<p>Also, the data sample is relatively small, but you are very welcome to test this idea into your environment. Just easy with freeproccache and flushprocindb commands!</p>
<p>This blog post was meant as a teaser,  to gather opinion from the readers. Couple of more additional approaches will be part of two articles, that I am currently working on.</p>
<p>As always, code is available at the <a target="_blank" rel="nofollow" href="https://github.com/tomaztk/Clustering_executed_SQL_Server_queries_using_R">Github</a>.</p>
<p>Happy SQLinRg!</p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tomaztsql.wordpress.com/3198/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/tomaztsql.wordpress.com/3198/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://tomaztsql.wordpress.com/2017/01/08/clustering-executed-sql-server-queries-using-r-as-tool-for/"> R – TomazTsql</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/B9p7OHYGP94"></a></div>