Writing Readable Code

Accessing and Changing Relational Data

Accessing and Changing Relational Data

Writing Readable Code

Here are guidelines for writing readable code:

  • Use comments to describe the program or script, including the author, the date, and a description of the modifications.

  • Put each major Transact-SQL clause on a separate line so the statements are easier to read:
    USE pubs
    SELECT au_fname, au_lname
    FROM authors
    WHERE state = 'CA'
  • Put Transact-SQL keywords such as SELECT and FROM, function names such as SUM, AVG, DATEPART, CASE, and CONVERT, and data types such as INT, CHAR, NTEXT in uppercase:
    USE pubs
    CREATE TABLE myauthors
     first VARCHAR(30) NOT NULL,
     last VARCHAR(40) NOT NULL,
     address VARCHAR(40) NOT NULL,
     city VARCHAR(30) NOT NULL,
     state VARCHAR(2) NOT NULL,
     zip CHAR(9) NOT NULL,
     phone VARCHAR(20) NULL
  • Define and use a style convention for object names consistently. Two typical conventions are:
    • Capitalize the first letter in each name part; do not separate name parts with underscores: TableName.

    • Make all characters lowercase and separate name parts with underscore characters (_): table_name.

    Even if the current instance of Microsoft® SQL Server™ is not case sensitive, readability is improved if a consistent style is used. It is good practice to always code object names in Transact-SQL statements using the exact same case as was used to define the object.

  • For objects that are common in your organization, define a set of standard abbreviations to be used consistently in object names.

  • Use single quotation marks for all character, string, binary, and Unicode constants, so that quoted identifiers are the only items that use double quotation marks (").

  • Use easy-to-type and easy-to-remember alias names when using multitable joins. For example, an alias of t for the titles table and an alias of a for the authors table.

  • If the information following a Transact-SQL keyword wraps to another line, consider tabbing the second and successive lines in one tab (usually five spaces) to make it easier to find the major keywords.

  • Use parentheses to indicate the execution order of complex mathematical computations. This allows for easier readability. For example, use "(price * 1.15) + sales" instead of "price * 1.15 + sales".

See Also