While it might be obvious that it's important to format your T-SQL code for readability, it might be less obvious that there's no agreed standard for how to format that code.
Everybody has their own style. The main thing. People will tell you all the time is just to be consistent. But then they'll tell you they don't like the format you've used.
Take a reasonable style and then to just keep applying it.
Here's an example of the core elements of a pretty standard style:
- T-SQL keywords capitalized i.e. SELECT
- Database object names PascalCased i.e. ProductGroups
- Local variables start with @ and PascalCased i.e. @Size
- Constants capitalized with underscores separating words i.e. MAXIMUM_INTEREST_RATE
- Blocks indented i.e.
One common variation is to use what's called snake_case instead of PascalCase. The words are all lower-case with underscores between them. I've seen arguments that snake_case is actually easier to read than PascalCase.
For indentation, I tend to work with four spaces as the Indent. Some People use tabs for this . There's a strong argument between People who love spaces and People who love tabs. It's not really something that I feel religious conviction about but I've heard it argued that having tabs instead of spaces has two benefits:
- People can adjust the tab size to suit themselves
- Tabs work better for people with visual disabilities, particularly with screen-reading tools.
Now there are many, many other standard rules, you might want to apply encoding, but these will get you started.
It's worth your while becoming proficient in SQL. If you'd like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.