When we first learn to program in any language, our primary concern is usually learning how to get the thing to work. We care very little about how it looks, adding descriptive comments, or how to use proper spacing between your statements. As I was learning T-SQL and other programming languages, one of the things I never appreciated enough was the importance of clean syntax. How your code is physically laid out on the page is almost always an afterthought. But it’s one of those small things that turns a good programmer into a great one!
The best way to illustrate the reason is to look at two simple examples. Both of these statements are the exact same code and accomplish the exact same thing. However, it doesn’t take very long to figure out which code is more pleasing to look at. Which one would you rather work with?
There are several benefits to having neatly-formatted TSQL code:
Being Considerate of Others
If anyone else ever has to read your code, they will thank you immensely for having a clean format and clear comments. Even if you have to go back and look at your own code, it is so much easier to understand the statements and what you were trying to do. If you have a team of multiple developers, take some time to decide on an agreed format and layout. There are huge benefits to having consistently written code across several people in a development team.
Easier to Debug
When the pieces are properly spaced and broken out, it becomes MUCH easier to troubleshoot any problems. For example, when commas are in front of each field in the SELECT clause, you can easily toggle them on and off to isolate what you need. Same with multiple criteria in the WHERE clause and the JOINS.
It seems like it would be slower to take the time to properly space things out and spend time formatting everything. But the reality is that the formatting allows you to work better and therefore faster in the long run. Nobody writes statements correctly the first time so we are constantly tweaking, enhancing, and troubleshooting. With clean code, that process happens much faster and efficiently.
Allows for More Advanced Code
In my opinion, this is probably the most important benefit. When reports get more complicated (and they will), it’s important that you spend your mental energy focusing on the logic and not the syntax. Clean syntax allows your brain to more easily process what’s in front of you and you don’t need to spend your time trying to interpret the statements. Use those brain cells to solve the logic and not the code!