An SQL query is used to retrieve data from a database. While formatting rules aren't always strict, scanning, troubleshooting and organizing code are much easier when you format an SQL query a certain way.
When it comes time to make changes to a query or figure out if something went wrong, you'll be glad you stuck to a few formatting rules. Even if you hire someone else to troubleshoot for you, they'll appreciate the cleaner code.
Keep Reserved Words Capitalized
As a general rule, keep all reserved words capitalized. For instance, use SELECT over select or Select. This makes them stand out when you're editing your queries. Even if your system highlights or color codes these words, format your SQL query by capitalizing all reserved SQL keywords.
Create A River
When you're trying to quickly scan to find errors, it's much easier if you format your SQL query using a river format. All your root keywords should line up so that a single line of space runs between all reserved keywords and their details. For instance, instead of:
SELECT first_name FROM contacts WHERE first_name = "Dave";
WHERE first_name = "Dave";
Notice the column or river that appears. At the very least, put each individual statement on a different line to keep things more organized.
When you're formatting an SQL query, you're not going to run out of space. The editor isn't like an actual piece of paper. You have plenty of room to space things out. Make the most of whitespace. For instance, add a few lines between individual queries or groups of code.
You could even add a quick note before each section of code to quickly identify areas when editing or troubleshooting. Overall, your code and queries look much neater this way.
Know When To Indent
Want to get confused when looking at your SQL queries? Just skip indenting. Yes, it really is that important. As a general rule to follow, indent joins and sub-queries. While they're both parts of your query, they also seem like they could be separate. This is why you indent - to show that they're attached to your main query.
Always indent when beginning a join or a sub-query. Follow the same rules for sub-queries as parent queries.
SQL Query Formatting In Action
If you'd like to see more formatting rules and tips or practice formatting SQL queries, see the following resources:
Do you have questions about SQL queries or need help implementing SQL Server in your business? Contact us today at 888-405-0029 or send us a message.
Image: Fabian Grohs