Category Archives: Imported from BeyondRelational

These posts are imported from my old blog page: http://beyondrelational.com/modules/2/blogs/77/nakuls-blog.aspx

SSMS – Query Designer – Ad-hoc query writing/editing made simple


The SQL Server Management Studio is truly an Integrated Development Environment. There are innumerable utilities and tools available within SSMS which are yet to gain a footing. Today, I will present how the Query Designer can be useful to develop ad-hoc queries – without writing a single line of T-SQL code!

Today’s post is thanks to Chintak Chhapia (blog), who is a dear friend & colleague from the day we joined office – 7 years ago!

The scenario

Let’s assume we need to query the Sales information in the AdventureWorks2008R2 database and attempt to list which Employee contributed to the sale. The traditional approach is:

  1. Launch SSMS
  2. Connect to the desired instance of SQL Server
  3. Begin with SELECT…

Now that we have written the first clause – SELECT, we have two options:

  1. Write the query by using Intelli-sense to reduce key-strokes
  2. Go with the dreaded SELECT * FROM….

Both of the above involve some writing, and when using Intelli-sense, we need to know about the table aliases, columns need to be searched for within the pop-up list. In short, writing a query would involve some typing and for most people, this would make query writing slower.

Not to mention that they query may or may not be formatted – the formatting would depend upon the beliefs of the query writer.

The Query Designer

SQL Server provides us a Query Designer using which we can write a query without a single keystroke. Here’s how:

  1. Login to your SQL Server instance using the SSMS
  2. Press Ctrl+Alt+Q or go to Query –> Design Query in Editor
  3. The Query Editor would launch. Notice that the SELECT…FROM is ready in the result pane (towards the bottom)
  4. image
  5. Scroll down and select the tables you need (you can multi-select using the Ctrl key). Let’s select the tables – HumanResources.Employee, Sales.SalesPerson, Sales.SalesOrderHeader
  6. Once the tables are selected, click on “Add” and then “Close”
  7. Notice that SQL Server automatically identified the links between the tables, and developed the “FROM” clause for us – ready with all the joins in place
  8. You can hover over the table links in the diagram pane to see the nature of the join (shown in the diagram is an INNER JOIN between HumanResources.Employee and Sales.SalesPerson)
  9. image
  10. Now, simply check the required columns from each table in the diagram pane and notice how SQL Server builds the “SELECT” clause of the query for you
  11. TIP #1 – Columns are added to the “SELECT” clause as you click the required columns. You can therefore control the column ordering by controlling the order in which you check-off the columns
  12. TIP #2 – You can then configure the sorting options, sort order, filter criteria and a lot of other things. Notice that the Query Designer will add the respective clauses as applicable
  13. image
  14. Once done, simply click OK
  15. You will be returned to the SSMS with the newly constructed, formatted query available for execution
SELECT     Sales.SalesOrderHeader.SalesOrderID, Sales.SalesPerson.TerritoryID, HumanResources.Employee.BusinessEntityID, Sales.SalesOrderHeader.OrderDate, 
                      Sales.SalesOrderHeader.DueDate, Sales.SalesOrderHeader.Status, Sales.SalesOrderHeader.ShipDate, Sales.SalesOrderHeader.OnlineOrderFlag, 
                      Sales.SalesOrderHeader.PurchaseOrderNumber, Sales.SalesOrderHeader.SalesOrderNumber, Sales.SalesOrderHeader.CustomerID, 
                      Sales.SalesOrderHeader.AccountNumber
FROM         HumanResources.Employee INNER JOIN
                      Sales.SalesPerson ON HumanResources.Employee.BusinessEntityID = Sales.SalesPerson.BusinessEntityID INNER JOIN
                      Sales.SalesOrderHeader ON Sales.SalesPerson.BusinessEntityID = Sales.SalesOrderHeader.SalesPersonID
WHERE     (Sales.SalesOrderHeader.OnlineOrderFlag = 0)
ORDER BY Sales.SalesOrderHeader.OrderDate, Sales.SalesOrderHeader.DueDate, Sales.SalesPerson.TerritoryID DESC

That’s it! You are all set – just click the Execute button, and the query will be executed!

image

Query Designer is for pre-existing queries also

The Query Designer is not just for new queries. If you have an existing query in SSMS, just select the entire query, and use the Ctrl+Alt+Q shortcut key or use the Query –> Design Query in Editor menu option. You will see that your query is now available in the Query Designer, ready for some key-stroke-less, graphical editing.

Until we meet next time,

Be courteous. Drive responsibly.

SSMS Properties Window – Get connection and query information with a mouse click


This week, I will go back to my trusted gateway to Microsoft SQL Server – the SQL Server Management Studio (SSMS). I will present before you two great features of SSMS which all administrators and developers would find useful.

SSMS Property Pages

When working on multi-server queries within the SQL Server Management Studio (SSMS), we often find the need to get a summary of the failed connections, number of rows returned, etc. Similarly, when studying a graphical query plan, many a times it is required to study the internals of a particular operator in greater detail.

One of the options by which we can explore further is to write a query (generally using a DMV) or using a textual execution plan. However, that does not have to be the case. Go to View –> Properties or hit F4 to launch the Properties window/page, which will help us in getting all of this information at the click of a mouse button.

The Properties Page consists of the following basic elements. This list stands true for all properties windows in SSMS.

  1. Mode Selector – see the list of properties & their values in a categorized form, or as a alphabetical list
  2. Property Name & Property Values columns
  3. Description pane, which gives a brief description of the particular property selected by the user

image

In the screen-shot above, you can see the default property page that comes up for a query in the query editor.

Property Pages when studying Graphical Execution Plans

When studying Graphical Execution plans, the Property Pages are a very powerful feature. Let’s write a sample query against a test SQL Server instance. Next turn choose to display the Estimated Execution Plan (Query –> Display Estimated Execution Plan, or press Ctrl+L).

USE AdventureWorks2008R2
GO
SELECT     Sales.SalesOrderDetail.SalesOrderID, Sales.SalesOrderHeader.RevisionNumber, Sales.SalesOrderHeader.OrderDate, Sales.SalesOrderHeader.DueDate, 
                      Sales.SalesOrderHeader.Status, Sales.SalesOrderHeader.ShipDate, Sales.SalesOrderDetail.CarrierTrackingNumber, Sales.SalesOrderHeader.CustomerID, 
                      Sales.SalesOrderHeader.SalesPersonID, Sales.SalesOrderHeader.TerritoryID, Sales.SalesOrderHeader.AccountNumber, 
                      Sales.SalesOrderHeader.PurchaseOrderNumber, Sales.SalesOrderHeader.TotalDue, Sales.SalesOrderHeader.Comment
FROM         Sales.SalesOrderDetail INNER JOIN
                      Sales.SalesOrderHeader ON Sales.SalesOrderDetail.SalesOrderID = Sales.SalesOrderHeader.SalesOrderID INNER JOIN
                      Sales.SalesPerson ON Sales.SalesOrderHeader.SalesPersonID = Sales.SalesPerson.BusinessEntityID AND 
                      Sales.SalesOrderHeader.SalesPersonID = Sales.SalesPerson.BusinessEntityID AND 
                      Sales.SalesOrderHeader.SalesPersonID = Sales.SalesPerson.BusinessEntityID INNER JOIN
                      Person.Person ON Sales.SalesPerson.BusinessEntityID = Person.Person.BusinessEntityID

The estimated execution plan for this query on my instance is shown below:

image

Now, let’s assume we want to understand more about the “Clustered Index Scan” operator applied on the index [SalesPerson].[PK_SalesPerson_BusinessEntityID]. All we need to do is to select the operator, and invoke the Properties page, which would look something like this:

image

For better search, here’s what you can get from the properties page:

  1. CPU cost
  2. I/O cost
  3. Number of executions
  4. Number of rows
  5. Operator cost
  6. Rebinds
  7. Rewinds
  8. Row Size
  9. Sub-tree cost
  10. Forced Index usage
  11. Logical Operation
  12. Node Id
  13. Database
  14. Index
  15. Index Kind
  16. Schema
  17. Table
  18. Ordered
  19. Output column
  20. Parallel execution
  21. Table cardinality

As you can see, this land-mine of information is just a mouse click away! That too, without a single query due to the use of graphical tools available out-of-the-box with SSMS.

So, the next time you are analyzing a query, or writing one, take a look at the Properties window – you will be surprised with what you will find.

Until we meet next time,

Be courteous. Drive responsibly.

Book Review – SAMS Teach Yourself SQL in 24 Hours, 5th Edition


SAMSRecently, I had the opportunity to review the newest SQL book, hot off the press – the SAMS Teach Yourself SQL in 24 Hours, 5th Edition. The book has been written by Ryan Stephens, Ron Plew & Arie D. Jones, and includes coverage of both – Oracle and Microsoft SQL Server implementations.

For 10 years now, the SAMS Teach Yourself series has helped kick-start the careers of millions of professionals around the world, and this book continues the tradition.

First impressions

The first thing that I realized was that this book was not about the specific implementation, but it is about the ANSI SQL standard, which to me increases the appeal even more. I am a strong believer in the fact that once the standard is known, implementations are not that hard to conquer. Every vendor will have their own version of the standard, but at the end, it’s all about combining the knowledge of the standard and logic to create practical solutions. This book does a very good job at explaining the standard, and earns points from me right from the start.

I am a Microsoft SQL Server professional, and I felt quite at home going through the book. The book follows a very balanced approach by explaining the ANSI standard first, and then following up with Oracle, Microsoft SQL Server & MySQL implementation samples, while explaining the differences between each!

Anatomy of the book

The book has been arranged into 24 chapters (or “hours”) spanning 8 parts (start from the very basics of a SQL query and go all the way to cover complex queries, performance, security & high-profile applications). Each chapter comprises of the following:

  • Step-by-step instructions
    • Every explanation is backed by a step-by-step walk-through of the SQL standard code
  • Quizzes & Exercises
    • The best part of the book
    • I enjoyed working my way through the Exercises & the Bonus Exercises in the appendices
  • “By the way” nuggets
    • These are interesting pieces of information, and would recommend spending some time thinking about them – each nugget has the potential to expand into hours of research
  • “Did you know?” moments
    • There are some hidden secrets about SQL and its various implementations in the book. I won’t spoil the experience by giving examples
  • “Watch out!” indicators
    • I would say, watch out for the Watch outs! – they are goldmines of information
    • Throughout parts 4 to 7 (Complex queries, Performance tuning, Security & summarized data structures), these parts will give experienced professionals a run for their money!

My recommendations to the reader

What I would recommend is that everyone – beginners and intermediates alike – must take the time out and run through the “Watch out!” and “By the way” sections. The Quizzes & Exercises (including Bonus Exercises) are also a must solve. Surprisingly, they gave me a flashback of all that I knew in Microsoft SQL Server – definitely worth spending the time.

For beginners though, I would recommend spending time out and gain background on entity relations (ER) and ER Diagramming. Once the reader knows what a relational database is, and what the key concepts are, this book would be a breeze. Remember that the book is about a standard and implementations, not about concepts.

Readers should not ignore the appendices either. They contain a summary of all commands learnt in the 24 hours, bonus exercises and answers to the exercises & workshops after each chapter.

Finally, here’s my biggest tip – don’t try to complete this in 24 hours back-to-back. The best ratio I found was to cover 1 hour (chapter) each day, and then spending the time to solve exercise, and conduct follow-up research/reading.

What I liked most?

I liked the fact that the book tackles following difficult concepts with ease:

  • Data-types
  • Complex Query & Performance tuning concepts
    • Go from the smallest table to the largest
    • Think about and arrange your WHERE clause to be the most selective – a concept also called as SARGability in the Microsoft SQL Server world
  • Basic database and server security

If I had to change one thing…

If I had to change one thing in the book, I would add a chapter, or an appendix on basics of relational databases. Readers need to understand that at the end of the day, the only relationship that exists is a 1:1 relationship between instances of entities (even a 1:N is multiple 1:1 relationships). Therefore, it is essential that the reader understands that a relational database is at its best if the user designs them in such a way that the query filters can be designed to return one and only one row (i.e. are most selective).

The final score

I would give this book a sound score of 4.5/5. Happy reading and best of luck with SQL!

I would like to thank Pearson education for giving me the chance to review the book. Best of luck!

Until we meet next time,

Be courteous. Drive responsibly.

“GO” as Batch Separator – Customize batch separator in SSMS & SQLCMD – What would you use instead of “GO”?


For years, Microsoft SQL Server developers and administrators have been familiar with a two letter verb – GO. “GO” is used as a batch separator, and we have never even thought of customizing the batch separator to be something other than “GO”. Here’s what Books On Line has to say about “GO”:

GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor.

SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server. The current batch of statements is composed of all statements entered since the last GO, or since the start of the ad hoc session or script if this is the first GO.

Recently, Madhivanan ( blog ) posted an interesting tip on the recently launched “Just Learned” page on BeyondRelational.com. He was talking about how the batch separator (“GO”) can be used as a loop – http://beyondrelational.com/justlearned/posts/75/go-command-is-also-a-while-loop-from-version-2005-onwards.aspx. Jacob mentioned that the batch separator can be customized, which got us (Madhivanan, Jacob & I) into an interesting discussion. Here’s the trail of thought that followed:

Customizing the Batch separator in SSMS

Here are a set of very simple, easy steps to customize the batch separator in SSMS:

  1. Launch SSMS
  2. Go to Tools –> Options
  3. Click on the “Query Execution” node
  4. Notice that we have an option to change the Batch Separator
  5. Change the batch separator
  6. Click “OK”

image

I changed the “GO” with “RUN”, and here’s the impact – it’s fun, isn’t it?

USE AdventureWorks2008R2
GO
USE AdventureWorks2008R2
RUN

Here’s what you would get if you run the first 2 lines above.

Msg 102, Level 15, State 1, Line 2

Incorrect syntax near ‘GO’.

Surprised? Don’t be – if you run the next 2 lines, you will see that our change has taken effect:

Command(s) completed successfully.

The good and the bad…

Customizing the batch separator is fun, but we soon encounter the dark side of the coin. Because SSMS is a client-side utility, these changes are restricted to you for the SSMS on your machine only. What this means is that if you share your SQL file with the custom batch separator to a colleague, they will encounter errors.

What this also means is that other SQL Server utilities like SQLCMD are unaware of this change!

Connect to your SQL Server instance via SQLCMD, and run the batch from above. Here’s what you would get:

image

Summarizing, customizing the batch separator is more a means of having some fun rather than some practical use.

Using a custom batch separator in SQLCMD

Let’s assume for a while that you want to continue using a customized batch separator, and use SQLCMD a lot. The best option is to explore the various options available with SQLCMD:

Microsoft (R) SQL Server Command Line Tool

Version 10.0.4000.0 NT INTEL X86

Copyright (c) Microsoft Corporation.  All rights reserved.

usage: Sqlcmd            [-U login id]          [-P password]

  [-S server]            [-H hostname]          [-E trusted connection]

  [-d use database name] [-l login timeout]     [-t query timeout]

  [-h headers]           [-s colseparator]      [-w screen width]

  [-a packetsize]        [-e echo input]        [-I Enable Quoted Identifiers]

  [-c cmdend]            [-L[c] list servers[clean output]]

  [-q "cmdline query"]   [-Q "cmdline query" and exit]

  [-m errorlevel]        [-V severitylevel]     [-W remove trailing spaces]

  [-u unicode output]    [-r[0|1] msgs to stderr]

  [-i inputfile]         [-o outputfile]        [-z new password]

  [-f <codepage> | i:<codepage>[,o:<codepage>]] [-Z new password and exit]

  [-k[1|2] remove[replace] control characters]

  [-y variable length type display width]

  [-Y fixed length type display width]

  [-p[1] print statistics[colon format]]

  [-R use client regional setting]

  [-b On error batch abort]

  [-v var = "value"…]  [-A dedicated admin connection]

  [-X[1] disable commands, startup script, enviroment variables [and exit]]

  [-x disable variable substitution]

  [-? show syntax summary]

I have high-lighted a particular parameter –c, which per Books On Line:

-c cmd_end

Specifies the batch terminator. By default, commands are terminated and sent to SQL Server by typing the word "GO" on a line by itself. When you reset the batch terminator, do not use Transact-SQL reserved keywords or characters that have special meaning to the operating system, even if they are preceded by a backslash.

Let’s try to use the –c parameter and supply our own batch separator:

image

The big question – If you had to, what would you propose as a replacement of “GO”?

I hope that you liked the discussion above, and a chain of thought has also started in your mind. What would you propose as a replacement of “GO”? I request you to post your thoughts in continuation to our original discussion at: http://beyondrelational.com/justlearned/posts/75/go-command-is-also-a-while-loop-from-version-2005-onwards.aspx as replies to this post.

Until we meet next time,

Be courteous. Drive responsibly.

July calendar – 5 week-ends after 823 years – Incorrect article by Times Of India


Today morning, as I was reading the morning newspaper and having a nice cup of tea, the following article grabbed my attention:

Edition: Times Of India, Ahmedabad edition
Date     : July 04, 2011
Page     : 08
Article : After 823 years, five weekends this July
Author : Chittaranjan Tembhekar

I was shocked! It is sad to note that a responsible print media fell into the trap of a rumour that seems to have started only to help numerologists and astrologists mint money.

Calendars are a periodic set of numbers and repeat approximately after a given time. This period however, is not a huge 823, but approximately 6-10 years.

Here’s the proof – such an arrangement of days last came about in 2005, and before that in 1994. Don’t believe me? See for yourself in your Windows calendar!

July 2011 image
July 2005 image
July 1994 image

 

Moral of the story: Don’t believe everything you see! Even the media may be wrong.

Until we meet next time,

Be courteous. Drive responsibly.