Skip to content

Formatting SQL Statements for Readability

    General Rules of Thumb

    • Follow some semblance of normalization
    • Identifiers (names of tables and columns) should be all lower case with words separated by underscores
    • Name your tables plural nouns (users, profiles, and posts)
    • Don’t use SQL keywords as column names (from, limit, order)
    • Use VERB_at for timestamps (created_at, updated_at, logged_in_at)
    • Use VERB_on for dates reported_on
    • ID is your primary key column (typically) _id is a foreign key
    • Use foreign key constraints
    • Keywords should be capitalized (SELECT, FROM, WHERE, GROUP BY, ORDER BY, ASC, DESC, JOIN, ON)

    How to Use Whitespace and Tabs

    You can put the select clause left aligned (example 1) and everything else 1 tab over. I have also seen it where you have all the keywords left aligned (example 2).

    Example 1

    SELECT *
         FROM table_name
         WHERE column = "criteria"
         GROUP BY column1, column2
         ORDER BY column1, column2

    Example 2

    SELECT
        column1,
        column2,
        column3
    FROM
        table_name
    WHERE
        criteria
    GROUP BY
        column1
    ORDER BY
        column2

    Turning in Your Query

    When you go to turn in your query it is quite easy to submit one file. Doing this correctly will make for easier grading, which in turn will allow you to get feedback quicker. If you turn it in as shown below, I can copy just the SQL code I need to run. Notice there is only one /* comment at the beginning and */ at the end.

    /* 
    QUEREY 1
    SELECT *
      FROM table_name
    
    QUERY 2
    SELECT *
       FROM table_name
    */
    Tags: