SQL TUTORIALS

SQL Tutorials: Query Formatting

%UPDATE% Picture of the word python written on a stick note.

DISCLAIMER: ANSI SQL (The SQL that's used universally) includes everything taught in this section. However, some of the syntax shown will vary between your Relational Database Management Service (RDBMS).

Welcome to the last Beginner-level tutorial! To finish off the basics, we will learn how to write clean SQL and best practices about formatting code. In this tutorial, we will cover how to write the cleanest SQL queries possible.

How to Write Clean SQL Code




Summary

  • In general, you should always follow your company's coding style guide. This ensures you keep within the company's guidelines and keep everything organized.
  • When naming SQL objects (such as Columns and Tables), always choose shorter, meaningful names, whether it's the object's actual name or an alias. Example:
    select name as product_name, AVG(price) as avg_price from products group by name;
  • In general, companies prefer to capitalize SQL keywords to help them stand out. Example:
    SELECT name AS product_name, AVG(price) AS avg_price FROM customers GROUP BY name;
  • When separating words in a name by spaces, it's typical to use either an underscore (_) or mash the words together and separate them with an uppercase letter. Example:
    SELECT name AS product_name, AVG(price) AS avg_price FROM customers GROUP BY name;
    OR
    SELECT name AS productName, AVG(price) AS avgPrice FROM customers GROUP BY name;
  • When writing code, readability is just as important as logic. If no one else can read your code, they can't fix any errors or implement any enhancements. To help with this, it's a common practice to separate your query on new lines with every keyword. Example:
    SELECT name AS product_name, AVG(price) AS avg_price
    FROM customers
    GROUP BY name;