Select Distinct and XML data

As you know, the DISTINCT key word can be used to eliminate duplicate rows from the result set of a query.  

For example:

If you run this query against the AdventureWorks2014 database you will get 19614 rows with many duplicates.

FROM [AdventureWorks2014].[Person].[Address]

As you can see in the above results set there are duplicates.  Albany appears  4 times. However, my goal is to simply see what cities the database has addresses in.

I can address this by using the DISTINCT keyword.  The code below show that you simply add it just after the SELECT keyword.  Here is a link for more information on DISTINCT.

FROM [AdventureWorks2014].[Person].[Address]

The result set below shows that Albany only appears one time, duplicates have been removed.

Well, what if the result set contains XML data?  Will the DISTINCT work the same way?  The answer is no.  

Since I was working on an example for my next performance class, I decided to use an example from that session.  In the query below the qp.* part of the column list will return a column named query_plan which is an XML data type.

SELECT DISTINCT pa.,cp.,qp.*
(SELECT plan_handle
FROM sys.dm_exec_cached_plans) cp
CROSS APPLY sys.dm_exec_query_plan (cp.plan_handle ) qp
CROSS APPLY sys.dm_exec_plan_attributes(cp.plan_handle) As pa
WHERE is_cache_key = 1 AND pa.attribute = ‘set_options’

However, when I add the DISTINCT keyword I get the error below.

So what do I do about.  You can simply use the CONVERT function to convert that datatype from XML to VARCHAR(MAX) like below.

SELECT Distinct qp.dbid
, qp.encrypted
, CONVERT(VARCHAR(MAX),qp.query_plan)
(SELECT plan_handle
FROM sys.dm_exec_cached_plans) cp
CROSS APPLY sys.dm_exec_query_plan (cp.plan_handle ) qp
CROSS APPLY sys.dm_exec_plan_attributes(cp.plan_handle) As pa
WHERE is_cache_key = 1 AND pa.attribute = ‘set_options’

Just a disclaimer, I didn’t analyze this for performance because the class is about an unrelated topic. If you plan on using this in production code, please assess the impact on performance.

I will put this into the “You learn something new everyday” category!   As always, it is always fun to learn and I hope you did as well.  Thank you for visiting my blog.

Lessons Learned From Three Months of Blogging

As the three month anniversary of my first blog post approaches, I thought I would share my thoughts on what I have learned so far.

Here is a list of what I have learned.

  • Have someone read your post before publishing
  • Blog about what is important or of interest to you
  • It is a great way to learn about SQL Server
  • Double check or even triple check your facts and code
  • Blogging isn’t a competition
  • Blogging can be easy or difficult
  • Be yourself
  • Have fun

Have someone read your post before publishing

I have found that this is a great idea.  There have been several times in which I have read my post the next day and found something in my post the I felt needed to be fixed.

These items include a number of areas including the following.

  1. Typos – this sadly happened far more than I would like to admit and included misspelled words and grammatical errors.
  2. Something missing – this is when I mention something in the post that I felt required some prerequisite knowledge that I didn’t mention earlier in the post. Sometimes, this also included an important detail that I simply forgot to include in the post.
  3. Out of order – This happened several times and it happened when I inadvertently placed something in the post earlier than it should have been.  This usually happened when I moved a part of the post to a new location using copy and paste.
  4. Sounded funny – There are times when I wrote something and it sounded great in my head but when I read it after I published it, it just sounded funny or awkward

These are all things that can be found by having someone else read your post.  That person does really need to know SQL Server to be able to help in many of these areas.  When something did slip through and I found it the next day,  I just hoped that I would be able to fix it before anyone read it.

Blog about what is important or of interest to you

When I first decided to start my blog, I talked to several experienced bloggers about what I should blog about.  My first thought was to blog only about topics that really haven’t been blogged about before.  I felt that with so many great bloggers out there, I didn’t think I could do it better.  However, I had several people tell me that I was looking at it wrong.  They suggested that I should pick a topic that is of interest to me and blog about that.  Even though there are many great SQL Server blogs out there, they told me that I would present a topic in a way that no one else has and someone just might connect with the way I say it.  This doesn’t mean that I would say anything better than anyone else, just in a different way.  If even one person has benefited by what I have written, it was worth the effort.  My goal is to help people become better at working with SQL Server.

It is a great way to Learn about SQL Server

Even though I have been teaching SQL Server for almost 20 years, there is always something to learn.  When I started my blog, I decided to blog about SQL Server basics to work on my blogging skills.  However, I found that I learned a lot more than just how to blog.  As I wrote my first blog post on the order of processing of the commands in a SELECT statement, I quickly realized that it is a great idea to go back to the basics sometimes to refresh your memory. Of course when blogging about something new, you will find that there is so much to learn.  Every blog doesn’t need to be very long or cover a complex topic.  Every day there are now SQL Server professionals who want to get better and learn more.

Double or triple check your facts and sample code

For years I found myself frustrated from time to time because of incorrect information or sample code that didn’t work.  This obviously requires knowledge of SQL Server to verify that your post is technically accurate.  Before releasing your post, my suggestion is to confirm the facts and run through your sample code to make sure it works as intended.

Blogging is not a Competition

The SQL Server community is a great community that is really about sharing and helping fellow data professionals.  If you attended PASS Summit, a SQL Saturday or a local user group you have seen this first hand.  The idea of sharing extends to blogging as well.  I believe that most, if not all of the blogs that exist are there to help others in the community.  Luckily there are many great blogs that I have used on a regular basis in my own career.  My goal isn’t to compete with any one, it is merely to put information out there and hopefully help as many people as I can.  As I said earlier, if I can help just one person, it is worth the time and effort.

Blogging can be easy or difficult

The beauty of having my own blog is that I get to decide if my blog posts are easy or challenging.  Some days, I feel like posting something that is more basic and others days I want to go down the more challenging route.  It is my choice.  What I have found for me is that I like to alternate between basic and more challenging.  This allows me to post a bit more frequently. Since there are always new people in the SQL Server community, there is always a need for the most basic topics.  You just need to decide what is best for you to blog about.  Keep in mind, there are always new people entering the SQL Server world and they could benefit from even the most basic blog posts.

Be Yourself

I feel that this is really important.  I am asked quite frequently for advice on teaching.  The first thing is always say is to be yourself.  That advice extends to blogs as well. Your blog should represent who you are.  If you are a bit more on the serious side, then let you blog show that.  However, if you consider yourself to be somewhat of a comedian, then let your blog show that as well.

Have Fun!!

I have found that I really do enjoy blogging.  The thought of helping is what makes it fun.  I have been lucky enough to have had the opportunity to teach SQL Server for almost two decades and blogging is just another method of teaching!!  I really look forward to what learning opportunities future posts will offer!!!

How to Start a Blog

Hopefully I have given some good advice on what to do once you have your blog up and running.  However, you may be asking yourself how do I start a blog.  Rather than reinvent the wheel, here is a blog post by Brent Ozar that gives some really good advice on how to start a blog. It is a number of years old, but I think still applies today.  How to Start a Blog

Some of my Favorite Blogs

These are just a few that I have used over the years.  The one that I almost always find myself at is Pinal Dave’s blog.  His was one of the blogs I consistently used when I first started my career and still use to this day.  If it weren’t for the many blogs that are out there, my career would not be where it is, for this I am grateful to the many folks that spend time sharing with us!!

Although I have learned a lot about how to blog, I still have so much more to learn!




Before we get into which is better to use, let’s talk about some UNION basics.  First of all, both UNION and UNION ALL are set based operations and the purpose of both of these statements is to combine two distinctly different result sets into a single set.  Let’s say I wanted to send a invitation to both employees and customers for an event, UNION or UNION ALL would work perfectly to allow me to get the list I am looking for.


The requirements for both UNION and UNION ALL are pretty simple.  Both queries must have the same number of columns and the columns must have similar data types.

Below is an example of a UNION query using the AdventureWorks2014 database.

FROM Purchasing.Vendor
SELECT Firstname + ‘ ‘ + LastName
FROM person.person

Even though the second query is using two columns from the Person.Person table, they are being concatenated into a single column.

So what happens if the number of columns do not match?  You will get this error.

Msg 205, Level 16, State 1, Line 1
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

This is a pretty easy error to fix, simply make sure the number of columns match.

Now on to the second requirement, the columns must be similar data types.  Notice that I didn’t say exact same data types.  If the data types are different, SQL server will use the data type precedence and do a convert to the same data types.  If you go here, you can see the data type precedence.  If you look at the image below, you will see that the BusinessEntityID is INT while the LastName is NVARCHAR.  According to the precedence list, INT is higher up the list than NVARCHAR so SQL Server will attempt to convert the LastName column data to INT resulting in this error.

Msg 245, Level 16, State 1, Line 8
Conversion failed when converting the nvarchar value ‘Abbas’ to data type int.

If you get this error, you will need to decide if you want to use the CONVERT or CAST functions to convert the column with the higher data type to the lower data type.  Obviously, the two columns mentioned is something you probably wouldn’t see in the real world, but I wanted to use it for demonstration purposes.


The differences between these two is pretty simple, when using just the UNION keyword, duplicates records will be eliminated while the UNION ALL will include any duplicates.

If you execute this statement against the AdventureWorks2014 database you will see that it will return 20,077 rows and will include duplicates.  If you run the same two queries with UNION instead of UNION ALL you will only get 19,622 rows.  Andrew Cencini will appear two times in the first query and only one time in the second.

Includes duplicates:

FROM Purchasing.Vendor
SELECT Firstname + ‘ ‘ + LastName
FROM person.person

Does not include duplicates:

FROM Purchasing.Vendor
SELECT Firstname + ‘ ‘ + LastName
FROM person.person

How can I tell what query each row is coming from?   In the query below you will see the text in pink, this is simply a string with a column alias.  In this case the string is the name of the table the row comes from with an alias of Source.

SELECT Name, ‘Vendor’ AS ‘Source’
FROM Purchasing.Vendor
SELECT Firstname + ‘ ‘ + LastName, ‘Person’ AS ‘Person’
FROM person.person

When doing this, the actual name of the column will come from the first query.  In the query above there are two aliases, Source in the first query and Person in the second.  The below image shows where the column name will come from.  Also notice the values in the column identify the source table for that row.


Of course in order to guarantee that the result set is to use the ORDER BY keywords.  When using UNION or UNION ALL, the ORDER BY must be after the last query.  If you try to use it in an earlier query, you will get this error.

Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword ‘UNION’.

What about performance?

Generally the UNION ALL will be faster than the UNION.  Here are a few links to some great posts that give more information about the impact on performance when using these statements.

Pinal Dave

Thanks for visiting my blog and please contact me if you have any questions.

Anatomy of a SELECT statement – JOINS – Part 4

If your database is normalized, data points will only appear in the database one time.  For example, a customer name will only appear in one table,  customer address will appear in only one table and employee names will only appear in one table. This is a nice Wikipedia article on Normalization Well, what do you do if you have a request to create a report on sales that has a requirement of containing both the sales person name and the customer name.  Since the sales person name is in one table and the customer name is in another table, you will need to use the JOIN keyword. Given that, the purpose of a join is when there are columns in different tables that you want in the same result set.

There are a number of join types that can be used in SQL Server. In this post we will cover the logical join, what you using in your code.

Logical Join Types


Behind the scenes the query engine will use physical joins.  There are four of these, Nested Loop, Hash Match, Merge and starting in SQL Server 2017, Adaptive joins.  Although it is important to know these when working on query optimization, these will be covered in a future post.

Logical Join Requirements

Before getting into the types of joins, we should review the requirements of joins.

  • Column names do not need to match
  • Data types must be compatible
  • SELECT list does not need to include columns from every table
  • Although not an absolute requirement, it is highly recommended that you use table aliases when joining tables

Keep in mind, if the data types are not the same, the data will have to be converted.  This can be done explicitly using CAST or CONVERT, or it will be done with an implicit convert.

What columns To Join On

Typically the join will be on the Primary Key column in one table and a foreign key column in another.  However, there are times in which this will not be the case.

Table Alias

When using joins, it is important to give your tables an alias.  When use tables aliases, I like to have them be somewhat descriptive, like e for employee or s for sales. I also like to keep them the same length when ever possible and keep the to three or less characters.  These are just my preference and in no way is a requirement.

If you don’t use any aliases and the columns are not referenced properly in the SELECT statement and the column name you want to use exists on one or more tables in the FROM clause you will get an error.

In the statement below, you will see that the ProductID column does NOT use the alias as expected. Also notice the error below it, “Ambiguous column name ProductID”. This simply means that the column name exists in more than one table and SQL Server does not know which table to get the column from.



An INNER join would be used when you want to return data that has matching values in both tables in the join.

For example, you want to see all the products that have been sold. In order for a query to pull this data, there needs to be a matching value in both tables.  Using the AdventureWorks2014 database, the Product information is in the Production.Products table while the products sold is in the Sales.SalesOrderDetail table.  If you look at the image below, you will see that the two columns that we need to join on are both named ProductID.  However, as I stated before, that is not a requirement, but something you will see quite often.  The data types for both of these columns are also the same data type, INT.  However, that is also not a requirement, they just need to be similar data types.


To meet the requirements of the request of seeing all the products that have been sold, the ProductID must exist in both tables.  If product ID number 1 was sold at least one time, you will see it in the ProductID column in the SalesOrderDetail table.  The image below visualizes this.  The green circle is the Product table while the orange circle represents the SalesOrderDetail table.  The points where the two circles cross represents the values that can be found in both tables.


Using the code below, we can query the AdventureWorks2014 database to find all the products that have been sold at least one time.  What makes this work is that a ProductID will be returned ONLY if it appears in at least one order.

SELECT p.productid
, p.Name
, s.ProductID
, s.SalesOrderID
FROM production.product p
INNER JOIN [Sales].[SalesOrderDetail] s
ON p.ProductID = s.ProductID
ORDER BY p.ProductID

When you run the above query, will the get the results below.  Notice that the result set is ordered by ProductID in ascending order.  You will also notice that the ProductID 1 does not appear, despite existing in the Production.Product table.  This is because ProductID has not been sold.

This is confirmed by using the two queries below, one for the Product table and the other for the SalesOrderDetail table. Since this is an INNER JOIN, it is expected that productid number 1 would not be returned in the above result set.

Another small note about the INNER JOIN is that it is a the default join type.  In the statement below, you will notice that the INNER key word is no longer present, yet returns the exact same results set as above.

SELECT      p.productid
, p.Name
, s.ProductID
FROM production.product p
JOIN [Sales].[SalesOrderDetail] s
ON p.ProductID = s.ProductID
ORDER BY p.ProductID


Lets change the requirements just a bit.  Instead of wanting to see all the products that have sold, we now want to know what products have NOT sold.  The OUTER join to the rescue!

An OUTER join will return all rows from the table on one side of the join and only matching values from the other table.

Starting with the LEFT OUTER JOIN, this join returns all rows from the table on the left and rows with a matching value on the left. We will use LEFT OUTER JOIN in this blog, however the OUTER key is technical optional, I just prefer to always use it.

SELECT p.productid
, p.Name
, s.ProductID
FROM production.product p
LEFT OUTER JOIN [Sales].[SalesOrderDetail] s
ON p.ProductID = s.ProductID

Below you will find the results of the above statement.  Notice that there are a number of rows that have NULL in the ProductID column from the SalesOrderDetail table.  This is what you will see when using an outer join and there is not a matching value in the table.  In this case, ProductID 530 does not have a matching value in the SalesOrderDetail table.


Of course if we switch this from a LEFT OUTER JOIN to a RIGHT OUTER JOIN SQL Server will now pull all the rows from the SalesOrderDetail table and the matching values from the Product table.

The code below is an example of a RIGHT OUTER JOIN.  All I did was change the word LEFT to RIGHT.  Now it will pull all the records from the SalesOrderDetail table and the matching values in the Product table.  One thing you will notice when you run this is that there not any NULL values in the p.productid column.  The reason for this is that referential integrity will not allow for a product that doesn’t exist in the Production.Product table to be entered into the table.

SELECT p.productid
, p.Name
, s.ProductID
FROM production.product p
RIGHT OUTER JOIN [Sales].[SalesOrderDetail] s
ON p.ProductID = s.ProductID

How are the LEFT and RIGHT tables determined

If you look at the two statements below, you will notice that the only difference is the last line.  In the first statement, the product table is listed first after the ON keyword, while in the second statement the SalesOrderDetail table is listed first.  Despite this change, both results had the exact same number of rows, 121,555.

SELECT p.productid
, p.Name
, s.ProductID
FROM production.product p
LEFT OUTER JOIN [Sales].[SalesOrderDetail] s
ON p.ProductID = s.ProductID

SELECT p.productid
, p.Name
, s.ProductID
FROM production.product p
LEFT OUTER JOIN [Sales].[SalesOrderDetail] s
ON s.ProductID = p.ProductID

However, if you switch the table order in the FROM clause, like in the statement below, you will see a big difference in the result set.

SELECT p.productid
, p.Name
, s.ProductID
FROM [Sales].[SalesOrderDetail] s
LEFT OUTER JOIN production.product p
ON p.ProductID = s.ProductID

This statement returns 121,317 rows.  This is every row from the SalesOrderDetail table and matching values in the Product table.  With some simple math, we can confirm this.  If you take the 121,555 and subtract the 212,317 you will get 238.  Using the code below, we will see that there are exactly 238 products that have not been sold. 

Now let’s get to the original question, what products have not been sold. In the example below we can simply add a WHERE clause and look for a any column from the right side table that is null.  The reason right side table, it because this is a left join.

SELECT p.productid
, p.Name
, s.ProductID
FROM production.product p
LEFT OUTER JOIN [Sales].[SalesOrderDetail] s
ON s.ProductID = p.ProductID
WHERE s.ProductID is null

When you run this you will see that there are 238 products that have not been sold.

Full Join

The code for this example can be found here: FullOuterJoin.

A full join is kind of a combination of the inner and both outer joins. Below you can see the two tables we will use for the example.

FROM TableA a
ON =

If you run the above code you will see that it returns all rows that have matching values in each table, all the rows that are in TableA and not in TableB as well as the rows in Tableb that are not in TableA.



A CROSS join is also known as a Cartesian product.  This type of join returns every possible combinations.

FROM TableA a

Below are the results.  The first ID column is from TableA while the second ID column is from TableB.  Notice that the results show each value from TableA and each value from TableB.  That is why you see 5 ones in the second column, there are 5 values in TableA.

Joining More than One Table

There are many times where you will need to join more than one table.  In this case we want to know the dates of each time a product was sold. In this case, we need to add the SalesOrderHeader table to our query. Although, there are three tables in the query, a join can only be between two table.

SELECT p.productid
, p.Name
, s.ProductID
, h.OrderDate
FROM [Sales].[SalesOrderDetail] s
INNER JOIN production.product p
ON p.ProductID = s.ProductID
INNER JOIN sales.SalesOrderHeader h
ON s.SalesOrderID = h.SalesOrderID


In a future post I will discuss the physical joins SQL Server will use to implement these logical joins.

Thank you for visiting my blog!!






Table Variable and Rollback

I am currently at PASS Summit in Seattle and learning a ton of new stuff.  There are a lot things that I have learned so far, but one thing really jumped out at me.  I attended Brent Ozar’s session on Cardinality Estimates and he showed that when you use table variables, the transaction does not get rolled back. That is what is great about SQL Server, there is always something to learn!!

If you run this code, you will see that when the select runs, it will actually not return any rows.

(Name VARCHAR(100))

    INSERT #Test




However, when you run this code, you will see that that rows are still in the variable even though the rollback command has completed.

(Name VARCHAR(100))

        INSERT @Testv



This is another reason why table variables should be used with caution. Table variables do not get statistics on the columns which of course can be a performance killer!!!

SSMS Options – Part 2

In SSMS Options – Part 1, I went over several options, including the color theme, track changes, line number and how to get to the options screen.  This post is a continuation of that post.  We will cover a few more options that could be helpful to you when using SQL Server Management Studio.

This post will cover these options

  • Select\Edit
  • Surround object names with brackets
  • Automatically populate Find What with text from the Editor
  • Show Errors


If you right click on a table in the Object Explorer, you will see a number of options, as seen below.  I would like to show how to use Options to change two of these, Select Top 1000 Rows and Edit Top 200 Rows.

These two options do exactly as they say, Select and return rows that you can edit.  Although, these options are here, I will still prefer and recommend that you write the DML statements needed instead.

When you use the “Select” option you will see something similar to what is below.  SSMS writes the DML statement for you and includes a comment at the top.  The results will be returned to you in a grid format.  However, it will return only the number of rows indicated.  In this case, 1000 rows.  You cannot edit these rows in SSMS without writing the proper DML statement.

However, if you click the “Edit….” menu item you can edit the data in the grid by clicking in the cell you would like to edit.  Although, as I stated before, I would recommend that you use the proper TSQL DML statement to complete data modifications.  When you do this, you will see the grid below.  You can now begin editing data.

When you do start editing you will see a small pencil just to the left of the first column.  Once you move to another record or close the table, the record will be saved.

Again, I would recommend that you use the proper DML statements to modify your data.  This looks like it might be a nice short cut…but I wouldn’t do it because the modification can fail.

The question you may have is, how do I change these values?  You will find the answer below.  Change these to what you feel is appropriate.  Notice that both state the TOP keyword, yet we cannot specify the column to do the order by.


Surround object names with brackets……

As you may know, when you drag an object name or a column name from the Object Explorer to the query window, SSMS will drop the name.  This setting will determine is SSMS place brackets around the name or not.


This option can be found, just above the two settings talked about earlier.  The values can either be True or False.

As expected, the results are below.

Automatically populate Find What with text from the Editor

This setting actually can make our lives just a little bit easier.  When this is turned on, SSMS will populate the Find What box with what is selected in the text editor.  You can find this setting in the location below.

If you click “Find and Replace” under the Edit menu, the box highlighted below will appear.  In the box will be what every you have selected in the text, as seen below.

Show Errors

This options can make it easier to locate the errors in your code.  First of all, if can be found under “Text Editor”.

When this is enabled, you will see a red indicator near the right scroll bar when there is an error.  Notice that it is actually on the line below the line that actually contains the error.

That is if there is one error.  Well, what happens if there are two or more errors. The statement below contains two errors, if you notice, the error indicator is on the line below the first error.

When the Show Errors option is turned off, you will not see it, just like in the image below.

Thanks for stopping by my blog!

Optimize for Ad Hoc Workloads

Optimize for Ad Hoc Workloads is one of those server level settings that are not changed very often, but is still good to know about. Before we get into the details let’s talk about what it is. When using SQL Server, it reserves a portion of memory for Plan Cache. The Optimize for Ad Hoc Workloads setting controls what SQL Server places into this plan cache for single use queries. When it is turned off, all single use queries will have the entire plan cached, therefore consuming more space. By turning this on, you are asking SQL Server to not store the entire plan when the query is executed the first time, SQL Server will now only store a plan stub instead. Which consumes less memory than the full plan would. Something to keep in mind, the next time that the query is executed, it will flush the stub from the cache and replace it with the full plan.

There are two methods you can use to determine if this settings is on or off. The first being SQL Server Management Studio(SSMS). In the Object Explorer right click on the server and then click on Properties.  The default is False, meaning that the entire plan will be placed in cache when a query is compiled and executed.

As with many things in SQL Server, you can also use TSQL to get this information. You will need to query sys.Configurations to get this setting via TSQL.

, value
, description
FROM sys.configurations
WHERE Name = ‘optimize for ad hoc workloads’

Here is the result of the above query.

How to determine if there are a lot of Single use Queries in Cache

I think there are two measures we need to understand when it comes to finding out what is consuming the cache. One is the amount of space being consumed by Ad Hoc queries and the other is the number of queries that are considered to be Ad Hoc queries.

Below is the Microsoft description of the dm_exec_cached_plans DMV.  This DMV can be use to capture the amount of space consumed by Ad Hoc queries.

“Returns a row for each query plan that is cached by SQL Server for faster query execution. You can use this dynamic management view to find cached query plans, cached query text, the amount of memory taken by cached plans, and the reuse count of the cached plans.”  – Microsoft

The code below uses the dm_exec_cached_plans to find out how much space in cache is being consumed by Ad Hoc queries.

From Pinal Dave:

AdHoc_Plan_MB, Total_Cache_MB,
AdHoc_Plan_MB*100.0 / Total_Cache_MB AS ‘AdHoc %’
WHEN objtype = ‘adhoc’
           THEN CONVERT(BIGINT,size_in_bytes)
ELSE 0 END) / 1048576.0 AdHoc_Plan_MB,
           SUM(CONVERT(BIGINT,size_in_bytes)) / 1048576.0 Total_Cache_MB
FROM sys.dm_exec_cached_plans) T

Below you will see the results of the above query.  Note that only 2.8% of the cache is being consumed by Ad Hoc queries.

So now let’s see how many Ad Hoc query plans are currently in cache.  The query below used a few additional funtions, sys.dm_exec_sql_text and  sys.dm_exec_query_plan, both of which accepts the plan handle as an argument value. 

SELECT SUM(c.usecounts)
, c.objtype
FROM sys.dm_exec_cached_plans AS c
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS q
GROUP BY c.objtype

The results are below

By looking at these two result sets you can see that although there are 2,542 Ad Hoc query plans in cache, they are consuming a small percentage of the total cache, 2.8%.

So what does this mean?  Well, although there are a lot of Ad Hoc queries, if the server is suffering from pressure in memory or in the plan cache, it is probably not due to the Ad Hoc queries.

How do I get the Query Plan

There is a post at that gives  really good explanation on how to get the query plan.

This code from the above link.  It not only tells us the query text and the plan, but also gives us the number of times that plan was used.

SELECT    cplan.usecounts
                , cplan.objtype
                , qtext.text
                , qplan.query_plan
FROM sys.dm_exec_cached_plans AS cplan
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS qtext
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qplan
ORDER BY cplan.usecounts DESC
Below is the result set from the above query.  With this, I can review the query and the execution plan for the Ad Hoc query.
Clear Cache
Of course restarting the SQL Server service will clear the cache, however there is also a method we can used to clear the cache without restarting.  We can use the code below.
When the cache is cleared, whether by a reboot or using the above command, you should let the server run for a bit to let the cache get reloaded with plans.
Does Case Matter?
When talking about the plan cache, case does matter.  However, they will both result in the same execution plan.
Using the AdventureWorks2014 database, when you run the following query you will see the plan in cache.
FROM [AdventureWorks2014].[Person].[Person]
Where BusinessEntityID = 3
The plan is below in the green box.  If you look at the other queries, you will also see the same query with one small difference, the “w” in Where is lower case.  Even though both queries will use the same Execution Plan.  The reason this happens I because SQL Server creates a hash of the query and if the hash value exists in the cache, it will use that plan.  However, because the “w” is a different case, the hash will also be different.
Let’s See it at Work
This is just a simple demo to show that when Optimize for Ad Hoc Workloads is turned on, the plan does not appear in the plan cache with the first execution, only the second.
First thing is to go to the properties of the server and make sure that the Optimize for Ad Hoc workloads is set to true.  Once that is done flush the  cache either by restarting the service or using DBCC FREEPROCCACHE.
Once that is done, run this code to confirm that there are not any plans in cache for the query were are about to run.
The query we are going to use is in the AdventureWorks2014 database:
SELECT * FROM Production.Product
Here is the code to check if there is already a plan in cache for this query.  Make sure to change the database ID, it is 8 on the system I am using.
SELECT c.usecounts
, c.objtype
, t.text
, q.query_plan
FROM sys.dm_exec_cached_plans AS c
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS q
WHERE t.text LIKE ‘%select% *%’ AND q.dbid = 8
ORDER BY c.usecounts DESC
Once you run the above code, you will see something similar to the image below.  Notice that there an entry for our query of the product table.
Now run the product table query.  Once you do you will see something like below.  As you can see not only is there a record for our query, but also a plan as well.  This is because the Optimize for Ad Hoc workloads is turned off.
Now, set Optimize for Ad Hoc workload to true, flush the cache and let’s see what happens.  Sure enough, no plan, just as before.
Run the following query:
SELECT * FROM Production.Product
then the query to get the plans.  When you do, you will see the record for the execution, but no plan.
Run the query for the products table a second time. Now you will see the plan is also in cache.  This is because the Optimize for Ad Hoc Workloads, when set to True only stores a stub in the cache on the first execution of a query, then the entire plan on the second execution.
As mentioned earlier in this post, spaces and case do make a difference when SQL Server queries the plan cache.  Notice below that there are two rows for what appears to be the same query.  However, if you look closer, you will see that the second query actually has an additional space between FROM and the table name.  This results in a different hash, and then results in a different entry in the plan cache.
Given all the information should I turn the on or off?
Well, that is a good question.  In my option, unless you have evidence that there is pressure in the cache, I would leave it at the default setting.  I have never actually had a need to change this setting, but am open to it if there is evidence it would benefit the overall performance of the server.  So let’s take a look at what others say.
“I can’t really give you a situation that I would expect to see where this shouldn’t be enabled honestly. There are theoretical examples out there – maybe a series of queries – lots of them – with reusable plans executed only twice. Or something like that. I answer a lot of questions on DBA.StackExchange – it’s a great site in a great network and the consensus there seems to generally be that it almost always makes sense in this answer. When I do a SQL Server Health assessment? I want to see that enabled.`”
Kendra Little Says this on her blog:

“Arguing about this setting is a lot like arguing about whether or not it’s better to put cream in your coffee: if the coffee is decent, it probably tastes fine either way.

My general preference is to not turn on a setting unless I have a good reason to believe that it will make a positive difference, so I don’t turn this on by default. Instead, I’d rather monitor the number of single use plans in cache, and investigate and act accordingly if that number starts spiking upwards.

But admittedly, that’s being fussy: if I had a flock of 1,000 SQL Servers to manage myself and I knew they were all patched to recent supported versions, I’d probably enable it on them all and I wouldn’t feel a bit bad about it, because I wouldn’t have the bandwidth to do it the very best, artisanal, hand-crafted way.”

Pinal Dave states this on his blog:

“Based on the result you can make your own conclusion and change your settings. I, personally, prefer to turn Optimize for Ad Hoc Workloads settings on when I see AdHoc Percentages between 20-30%. Please note that this value gets reset when you restart SQL Server services. Hence, before you change the settings, make sure that your server is up for a quite a few days.

If you are not sure, what to do, just reach out to me with the result and I will be happy to help you.

One final note, This is just one settings, which contributes to your SQL Server Performance”

I tend to be more in line with what Pinal Dave is saying with the understanding that this is only one setting, however all three make very valid points.  You need to look at the big picture and decide for yourself on what the best settings is for your systems. There are a number of other SQL Server settings that could impact performance and you should review them all before making a change.  You should look at the big picture for performance to determine if the server could benefit by changing this setting.

Thanks for stopping by my blog….

SSMS Options – Part 1

We all use SQL Server Management Studio on a daily basis.  Although many of the options you will more than likely not change at all.  There are a few that would be good to change to help enhance our experience in SSMS.  This post, as well as a few future posts will go over a number of these options.  The thing to remember when changing options in SSMS, some change will require a restart of SSMS.  I will point these out as I cover the various options.

Obviously, the logical starting point is to go over how we get to the options form.  In SSMS you go to the “Tools” menu, under which you will see the “Options…”menu.

Once you click Options you will see this..

There are many options available that can be changed.  These options will not only change the way SSMS behaves, they can also change how it looks.

When you first look, on the left you will see a tree structure.  If you see an arrow to the left of the menu item, there are more options under that you can see when you click it the menu item.  You can see this in the image below.

As you can see, there are a ton of options.  If you are not sure of the exact name, you can search the options.  In the upper left hand corner of the Options window, you can enter the words you are looking for and SSMS will return all the options that have that word.


Color Theme

This can be used to change the over all appearance of SSMS.  With this option you have two choices, Blue and Light.  Blue is the default.  This does not require a restart of SSMS.


This give a darker look to SSMS. The borders are blue and the headers are blue as well.


As the name would imply, this turns SSMS into a light colored theme.


Track Changes

This option is used to track any changes you have made to the TSQL you are working with.  You can find this option under “Text Editor”.  Changing this does not require a restart of SSMS and is on by default.

When this option is turned on, you will see a yellow bar on the left side for every line you modify.  Once you save the file, the it will turn to green.  Like the two images below.

Line Number

This option is off by default.  Some folks like to turn this one, some prefer it off.  Personally I usually have it off.

When this option is turned on, you will see the line numbers on the left side.  When you copy the code, it does NOT copy the line numbers as well.


In order to keep the post kind of short, I will do another post on additional options that you might want to learn about.

Thanks for stopping by my blog and hope you learned something.

And we wait!!

Since I am at the airport waiting for a very delayed flight to take off, I thought it would be appropriate to do a post on…WAITFOR!!

As expected, this statement can be used to pause the execution of a batch.  It can also be used to have a batch wait until a specific time to continue the execution.

There are really two options, DELAY and TIME.


The DELAY argument is used to pause the execution of the batch.  You can force a batch to wait for up to 24 hours.  This argument uses the “Time To Pass” value to determine how long to wait.  This really means, how much time has to pass before execution of the batch can continue. You cannot pass a date into this argument, it must be a time in the following format: hh:mm:ss.msss.  The time passed must not exceed 24 hours.  If the time does exceed 24 hours, you will get the following error.

If you put WAITFOR DELAY ’23:59:59′, this will run fine, however, if you put WAITFOR DELAY ’24:00:00′, it will fail with the same error as above.


The TIME argument is used to have a batch pause and continue executing at a specific time.  You will hear this referred to as “time_to_execute”. This argument has the same 24 hour limitation as the DELAY argument.  If you attempt to run this, WAITFOR TIME ’25:48:00′, you will receive the same error as above.

In the code below, the batch will execute the first SELECT and then wait until 1:48 AM to execute the second SELECT.

FROM [Person].[Person]

WAITFOR TIME ‘1:48:00’

FROM [Person].[Person]


When specifying a time, you can use 24 hour time, WAITFOR TIME ’13:48:00′ or you can use AM/PM, WAITFOR TIME ‘1:48:00 PM’.

A point of caution if using WAITFOR in production code, make sure that by using it you are not increasing the timeouts in the application.  You may need to adjust the timeout setting of the application.  Also use a great deal of caution if using this in a can make for a bad day!!

Keep in mind, the time specified starts when the thread is scheduled.  If there is a delay in scheduling, it may actually wait longer than expected. This can happen on really busy servers.

The statement below is also important to remember if you decide to use WAITFOR a lot.

“SQL Server monitors the number of threads associated with WAITFOR statements, and randomly selects some of these threads to exit if the server starts to experience thread starvation.” – Microsoft

Per Microsoft, you need to be careful using this because you can potentially increase the number of deadlocks.

Here is a link to Microsoft’s page on this topic.

Here is a very good video by Burt Wagner. I like that he has a stored procedure named:  BuyDonuts!!!

Thanks for visiting my blog.

SSMS Options – Change Font Size

This is the first of a series of posts to go over the properties of SSMS that can be changed.  I will post these from time to time, many times after I need to use one of them.

To access the Options, you have to go to the Tools menu in SSMS and then click on Options.

When you do this, you will see the screen below. As you can see, there are a ton of options that you can change.  Some are for the Database Engine while some are for SQL Server Analysis Services.  Some are even for Azure or AlwaysOn. For this post we will talk about how to change the font size.

Starting with changing the font when you write queries.  Under the Environment group go to “Fonts and Colors” then simply change the font size.  When you make this change, it takes effect immediately.  No need to restart SSMS. As you can see, you can also change the color and the background color.

Although the focus of this post is the Text Editor, you can also use this to change the font in many different aspects of SSMS.

When changing settings, you must be aware that some settings will require that you restart SSMS. For example, changing the Grid Results will require a restart.  You will see the message below.

As I said before, you can change the font size of many aspects of SSMS, including the result set.  Below is how you can change the size of the Grid font. Simply change the “Show Settings for” to “Grid Results”.  Then change the fonts as you see fit.

This is what the results grid looks like with the default font.

Now let’s change the size of the font to 16. As you can see below, the font is larger and easier to read.

Here is an example of what you will see if you change the font for Extended Events.  This is so much easier for me to read.  This is just an example of the far reach of the Options menu in SSMS.

Font Colors

When writing TSQL, there are many font colors you will see.

Keywords are blue, strings are red, object names are black and comments are green.  You can change these if you like.  Below is an example of the default font colors.
If you decide you would like to change the colors of fonts, you can do so by selecting the proper word type, inside green box below,  and then modifying the settings.  This screen also gives you an example of what the text will look like.

I change the font size when I am presenting so attendees in the back of the room can see the code better.   I like this option because you can adjust your SSMS environment that works for you!

Thanks for stopping by my blog!!