Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Data Management

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Your profile

    Search

    XML Feeds

    Google Ads

    « SQL Server Code Name "Denali" CTP3 is available for download2011 Quarter 2 Goal Review »
    comments

    Here we go again! It’s T-SQL Tuesday #20 – a monthly blog party, this time hosted by Amit Banerjee. (Thanks Amit!) This month, we’re talking about “T-SQL Best Practices”.

    I used to write a lot more T-SQL than I do now. I had lots of rules for how T-SQL was written in my shop. But rather than sharing that extensive document, today I want to share with you my top three pieces of T-SQL advice.

    KISS (Keep It Simple, Developer)

    There are a lot of ways to solve problems in T-SQL. Once you get beyond a simple SELECT or UPDATE, you can really start playing. Derived tables, Common Table Expressions, CASE statements, aggregation, cursors, window functions, functions, pivoting…the things you can play with are endless. One of the beautiful things about T-SQL is that there is almost always more than one way to solve a problem.

    Remember, though, to keep it simple. Someday, someone else will need to read that code, and interpret it, and possibly (gasp) edit it. It could even be you.

    Table Aliases

    No, you don’t need to ask people in the office to start calling you by your Twitter handle (no matter how funny that would be). SQL Server includes a “correlation name” or “range variable” to make FROM statements more easily readable. It’s also known as a “table alias”.

    A table alias is easy to implement, and saves trouble in the long run. How? Let’s look at this simple query:

    1. SELECT Customer.CustomerID, SalesOrderID, OrderDate, TotalValue
    2. FROM Customer
    3. INNER JOIN SalesOrder ON SalesOrder.CustomerID = Customer.CustomerID

    It’s a pain to reference a field with the full table name. And while this query is readable, what table does “OrderDate” reside in? Can you easily tell?

    Try this version instead:

    1. SELECT CUST.CustomerID, SO.SalesOrderID, SO.OrderDate, SO.TotalValue
    2. FROM Customer CUST
    3. INNER JOIN SalesOrder SO ON SO.CustomerID = CUST.CustomerID

    With a table alias:

    Right away, reading the SELECT statement, I can tell which tables the fields are being pulled from.

    When I want to use a field that is in multiple tables with the same name, it’s faster to type the above then “Customer.CustomerID” or “SalesOrder.CustomerID”.

    If I need to join a table to itself, I have to alias the table names. Easily understandable aliases are important in that situation.

    A few notes about table aliases:

    Make them easy to understand – “a”, “b” and “c” are, usually, meaningless.

    Use aliases for every field – you don’t know when you’ll need to add another table to that query, and if that table may have a field of the same name.

    Be consistent – if you use “CUST” in one query, use it in the next.

    Avoid Implicit Conversion

    Every field in a table is assigned a data type – int, varchar, datetime, image, etc. When you join two tables together, or do comparisons in a WHERE clause, SQL Server is going to evaluate the data types of the two fields. If they are the same, no problem – they will happily and easily be matched or compared.

    But what happens when you try to compare an int and a varchar, or a varchar and a datetime? (insert ominous music here) The dreaded implicit conversion. This will negatively impact the performance of your queries. I have (of course) been meaning to write a blog post on this for some time, but have not. One good blog on this is from Jonathan Kehayias (twitter | blog): Unexpected Side Effects? Problems from Implicit Conversions. Another informative blog post comes from Mike Walsh (twitter | blog): You Could Be Suffering Right Now.

    The easiest way to avoid implicit conversion is to have a well-designed database. However, if that is out of your control (perhaps it’s a legacy database, or a vendor-supplied system), make sure you know what data types your fields are, and pay attention to that when writing code.

    Don’t Write Good Code, Write Great Code

    By taking a little time to develop some standards and follow them, and understand the nuances of T-SQL, you can do more than write good code. You can write great code.

    I am excited to read the other T-SQL Tuesday entries!

    About the Author

    User bio imageJes Schultz Borland is a Consultant with Brent Ozar Unlimited, and a Microsoft SQL Server MVP. She holds an AAS - Programmer/Analyst degree, is a Microsoft Certified Professional in SQL Server 2012, and has worked with SQL Server as a developer, report writer, DBA, and consultant. Her favorite topics are administration, automation, and SSRS. She is an active member of PASS, President of FoxPASS, founder of Tech on Tap, and a LessThanDot.com blogger. She frequently presents at user groups, SQL Saturdays, and other community events. She is also an avid runner and chef.
    Social SitingsTwitterLinkedInLTD RSS Feed
    InstapaperVote on HN

    6 comments

    Comment from: Eli Weinstock-Herman (tarwn) [Member]
    Eli Weinstock-Herman (tarwn) Excellent. One I though of while reading the naming part is to write with a clean, consistent layout. It saves a lot of time and energy if everything is spaced out nicely and easy to read, and the if you're worried about the few extra bytes for carriage returns or spaces you probably don't have enough disk for the real data :P
    07/12/11 @ 06:46
    Comment from: Justin Dearing [Visitor] · http://www.justaprogrammer.net
    Justin Dearing Great article Jes. Personally, I tend to avoid aliases because they tend to be overused, and shrunk down to 2 characters making them hard to read. In my old age I've come back around to them though.
    07/12/11 @ 07:36
    Comment from: SQLNightOwl [Member]
    SQLNightOwl Love it! I've been stressing to my folks that if the query contains more than one table then you *must* include where you're getting the column. This prevents code that had been working fine from mysteriously breaking. Assume they add the column TotalValue to the Customer table (sum of all orders). If they aren't explicit (code sample 1) then the query breaks and the developer has egg on their face (not in the good way from eating). Being explicit is always the better option.
    07/12/11 @ 07:48
    Comment from: SQLDenis [Member] Email
    SQLDenis Nice article...

    The same goes for insert statements
    For example instead of

    INSERT BLA
    VALUES()

    I would do


    INSERT BLA(column list)
    VALUES()

    that way if they add 2 columns with defaults later on it won't break any of your code


    Now the question is do you alias like this

    TableName Alias

    or

    TableName AS Alias

    07/12/11 @ 12:18
    Comment from: Jes Schultz Borland (grrlgeek) [Member]
    Jes Schultz Borland (grrlgeek) Denis - good question! The AS is not required in aliasing. I used it for quite some time. However, after a while, it just became extra typing. My preference is not to use it. I'm going to go with "be consistent". If you use it once, use it always.
    07/12/11 @ 13:18
    Comment from: Naomi Nosonovsky [Member]
    Naomi Nosonovsky For discussion about using AS or not I just found this link
    http://beyondrelational.com/blogs/madhivanan/archive/2007/11/14/should-alias-names-be-preceded-by-as.aspx

    which in turn points to Denis article.

    I personally use AS for column aliases and don't use it for tables.
    07/13/11 @ 09:46

    Leave a comment


    Your email address will not be revealed on this site.

    To mislead the spambots.

    Your URL will be displayed.
    (Line breaks become <br />)
    (Name, email & website)
    (Allow users to contact you through a message form (your email will not be revealed.)