SQL SERVER – Tips from the SQL Joes 2 Pros Development Series – Efficient Query Writing Strategy – Day 4 of 35

Answer simple quiz at the end of the blog post and –
Every day one winner from India will get Joes 2 Pros Volume 1.
Every day one winner from United States will get Joes 2 Pros Volume 1.

Query Writing Strategy

Some people may push back on this next technique or misunderstand until getting to the very end. The goal is to have fewer errors as you write complex queries more quickly by making sure the easy stuff works first.

If you are a SQL expert who only works on the same database for the rest of your life who will never type the wrong field name in a query then yes you are the fastest query writer your company could ever have. Let’s face it, sometime we as SQL experts need to get familiar with our underlying data before we get great coding velocity. Brute force or memorized keystroke solutions can be fun when learning but not good when you have a deadline and want to write queries quickly, with fewer errors, and test things as you continue to write more code. With that in mind here is something I have yet to find in any book. When enthusiastic SQL students do this, they experience a revelation. The number of errors drops significantly and the speed at writing complex queries increases immediately.

Knowing how to narrow down what you are looking for amongst a vast list of choices helps immensely. Grabbing the right tables first and then the fields second is much like grabbing the right menu before ordering an item from it. In fact, one student named Tim took this back to his team of SQL developers and they immediately implemented this process.

We are all used to following steps we know have proven to work. Most of the time, actions are sequential from top to bottom or left to right. Other times we complete things in phases. The two phases you are going to see here apply to joining tables or any other query that has plenty of logic. Just remember to organize first and clean up (or itemize) second.

When you go to a new restaurant, you ask to see the menu. You want to see all they have to offer. The odds are you may like half the items, but only need a few for to feed your family. Looking at the menu is like starting off with a SELECT *. After looking at all the fields, you pick the one(s) you want.

Sometimes restaurants have multiple menus. My favorite restaurant has a kids’ menu, an adult menu, a “gluten-free” menu and a drink menu. These menus were gathered at our station. Ultimately, in my head, a selection was narrowed to what our group needed.

Phase I:  Organize. When you’re building a new query from many tables, you’ll find yourself wondering, “Where do I start?” Really there are three steps to this phase.  First, lay the steps out by identifying which tables contain the essential data. Second, get all your joins working with a SELECT * statement. Third, add any basic filtering criteria.

Phase II.  Itemize. Once all joins and criteria, such as SELECT *, FROM and WHERE are working, you are ready for Phase II. This entails going back and changing your SELECT * to an itemized select field list as your final step.

Let’s explore how this two-phase process of “Organize then Itemize” is a time-saver. We are going to use one of the challenges from the last lab. In Lab 3.2 (Outer Joins) in Skill Check 2, you needed to get four fields from two different tables. If you list all four desired fields and test one table at time, you get an error as seen on the right side of Figure 4.1.

In Figure 4.1 we write the SELECT statement and part of the FROM clause. The FROM clause will have two tables when we are done, but for now we just want to get the Location table working. When we use the SELECT * it removes any possible errors from line 1. From there, we can focus on our more complicated join logic. We can add tables one at a time until all is working. This is the Organize phase.

SQL SERVER - Tips from the SQL Joes 2 Pros Development Series - Efficient Query Writing Strategy - Day 4 of 35 j2p_4_1

SELECT * never results in an “invalid column name” error, but a SELECT list can. After your query is organized and working, you can go back and itemize the SELECT field list to display just what you want. This is the Itemize phase. These steps are broken down as follows:

--ORGANIZE PHASE: Get SELECT * query written.
-- Test first table logic
SELECT *
FROM Location
--Test second table with join
SELECT *
FROM Location INNER JOIN Employee
ON Location.LocationID = Employee.LocationID
--Test all tables with criteria
SELECT *
FROM Location INNER JOIN Employee
ON Location.LocationID = Employee.LocationID
WHERE [State] = 'WA'
--ITEMIZE PHASE: Change to SELECT field list
--Choose your fields
SELECT FirstName, LastName, City, [State] FROM Location INNER JOIN Employee
ON Location.LocationID = Employee.LocationID
WHERE [State] = 'WA'

SELECT is always the first statement in a query. It’s natural to want to finish your SELECT statement before writing the FROM clause. Start with SELECT * and finish the query. Do your field list when all else is done. Use this method and you will never again get a field selection error while building queries.

Note: If you want to setup the sample JProCo database on your system you can watch this video.

Question 4

Q. 4) Square brackets are required when…

  1. The table name conflicts with a keyword
  2. The table name is the same as another table.
  3. The table uses the same name as the database.
  4. To alias the table.

Please post your answer in comment section to win Joes 2 Pros books.

Rules:

Please leave your answer in comment section below with correct option, explanation and your country of resident.
Every day one winner will be announced from United States.
Every day one winner will be announced from India.
A valid answer must contain country of residence of answerer.
Please check my facebook page for winners name and correct answer.
Winner from United States will get Joes 2 Pros Volume 1.
Winner from India will get Joes 2 Pros Volume 1.
The contest is open till next blog post shows up at which is next day GTM+2.5.

Reference:  Pinal Dave (https://blog.sqlauthority.com)

Joes 2 Pros, SQL Scripts
Previous Post
SQL SERVER – Tips from the SQL Joes 2 Pros Development Series – Finding Apostrophes in String and Text – Day 3 of 35
Next Post
SQL SERVER – Tips from the SQL Joes 2 Pros Development Series – Finding un-matching Records – Day 5 of 35

Related Posts

204 Comments. Leave new

  • Correct answer is No. 1: Square brackets are required when the table name conflicts with a keyword

    Malay Shah
    Ahmedabad, India

    Reply
  • Jitesh Chhagnani
    August 4, 2011 2:29 pm

    Hi Pinal,

    The answer is – option 1

    Q : quare brackets are required when…

    1. The table name conflicts with a keyword

    The brackets can be used when column names are reserved words.

    If you are programatically generating the SQL statement from a collection of column names you don’t control, then you can avoid problems by always using the brackets.

    Reply
  • Nakul Vachhrajani
    August 4, 2011 2:39 pm

    While there can be many scenarios to use square brackets (I use them as a standard practice in my production code for all columns), but out of the proivded choices only one scenario is when use of square braces is mandatory:

    Correct Answer: #1. The table name conflicts with a keyword

    Why?
    Database object names are identifiers (literal strings). The rules for an identifier clearly state that:

    The identifier must not be a Transact-SQL reserved word. SQL Server reserves both the uppercase and lowercase versions of reserved words.

    When identifiers are used in Transact-SQL statements, the identifiers that do not comply with these rules must be delimited by double quotation marks or brackets.

    Reference:http://msdn.microsoft.com/en-us/library/ms175874.aspx

    By the way, contrary to popular belief, one can have a table name same as the database name.

    Country of residence: India

    Reply
  • Correct Answer is – 1

    ‘STATE’ is the reserved keyword in SQL Server.

    Reply
  • Amit Choudhary
    August 4, 2011 3:02 pm

    answer is 1) The table name conflicts with a keyword

    It works as a qualifier and considering them local to the DB names those are similar to keywords in SqlServer.
    another reason when we have spaces in the table/column names.

    Country of residence: INDIA
    Mincracker network.

    Reply
  • Answer 1 is correct

    The table name conflicts with a keyword.

    Country of residence: INDIA

    Reply
  • Devang Raval

    Correct Answer is 1) The table name conflicts with a keyword.

    As SQL Server has its own sets of keywords and if you choose to keep same name as these reserved key words you need to tell SQL Server with Square bracket that this is not SQLServer Reserved Key Word.

    INDIA

    Reply
  • Correct Answer: 1. The table name conflicts with a keyword

    Reply
  • Chirag Satasiya
    August 4, 2011 3:47 pm

    Hi pinal sir,
    Concept of article is really simple but very useful in broader level.

    The correct answer for this question is option no. 1:

    “The table name conflicts with a keyword”

    Reason:
    The brackets are required if we use keywords in the column names.
    In our case state is column of location table and also state is sql keyword used reserved for future release of SQL server.

    Regards
    Chirag Satasiya(Mumbai – INDIA)

    Reply
  • Shatrughna Kumar
    August 4, 2011 3:52 pm

    Option 1.The table name conflicts with a keyword

    New Delhi
    Shatrughna

    Reply
  • Correct Answer is Option 1.The table name conflicts with a keyword

    Ahmedabad, INDIA

    Reply
  • Correct Answer is Option 1 :

    The table name conflicts with a keyword

    Country of residence: INDIA

    Reply
  • Jigar Badgujar
    August 4, 2011 4:06 pm

    Answer : 1

    1.The table name conflicts with a keyword

    Square brackets are mandatory whenever user provide a column name or table name which is actually the built in SQL Server function or Keyword or else the name have space in it.

    2 . The table name is the same as another table.
    we can not have duplicate table name in any case in SQL server in same database.

    3. The table uses the same name as the database.
    no requirement of square branckets.

    4.To alias the table.
    Only when alias is the default sql server keyword or it contains space in between than square required.

    Thanks & regards,
    Jigar Badgujar
    India

    Reply
  • 1. The table name conflicts with a keyword

    Reply
  • Tearati Sudhakar
    August 4, 2011 4:12 pm

    1. The table name conflicts with a keyword

    Reply
  • Vishal S Jindal
    August 4, 2011 4:26 pm

    Answer : option 1 is correct

    table name keyword conflict with keyword/ reserved word

    more

    you can use any unqualified / invalided character that are not allowed in identifier if you use []

    country : india, ahmedabad

    Reply
  • Dayanand Singh
    August 4, 2011 4:38 pm

    Correct answer is option 1

    In MSSQL Square brackets are used in order to remove the confusion for query execution. It may be due to confliction with reserved keywords, use of special character or space in names of DB objects etc.

    Country – INDIA (Gujarat)

    Reply
  • Mandar Alawani
    August 4, 2011 4:54 pm

    Correct answer:

    1.The table name conflicts with a keyword

    Thanks,
    Mandar
    Mumbai, INDIA

    Reply
  • Answer: 1. The table name conflicts with a keyword

    Reply
  • Dear Pinal Sir,

    Answer is The table name conflicts with a keyword

    Reply

Leave a Reply