1. Write readable code
In the previous lesson you've learned how to be kinder to the future you and anyone else reading your SQL scripts by using techniques to better convey the intent of these scripts.
But, what is clearly conveyed intent if the code is hard to read. And SQL is a language that gets progressively harder to read the longer the script gets.
To deal with this challenge, this lesson will introduce you to some best practices you can do to make your SQL code easier to read.
2. Capitalize SQL commands
First, always capitalize SQL commands and leave the rest of your code lower case. In the example to the left, without any syntax highlighting you have to review each word to know whether it is a command.
If, instead, each SQL command is capitalized, as in the example to the right, it makes it much easier to differentiate between commands and everything else.
3. Use new lines & indentation
Next, don't be shy to use use more spacing and more lines of code.
Although it is possible to write all of your code in one super-long line it doesn't mean it's a good idea. Judicious use of indentation can make code far easier to read.
Let's compare the example on the left to that on the right. The use of new lines for each column makes it clear which columns are being returned. The use of new lines for each conditional command along with the indentation helps it stand out.
4. Use snake_case
The lack of spaces in tables and columns names can make code hard to read. To help with this, make sure to add an underscore wherever you need a space when naming tables and columns. This is called snake case and it makes code much easier to read.
5. Use IN instead of many OR statements
The next strategy is to use the IN command instead of multiple OR commands.
Rather than writing many OR statements for the same column, as shown in the example on the left, use the IN command to clearly list the conditions you're filtering for.
6. Use BETWEEN when possible
Similarly, rather than writing multiple statements using inequalities to filter a numeric column, instead use the BETWEEN command as shown in the example on the right.
7. Let's practice!
SQL scripts can easily become challenging to decipher, this is why it is critical to make these scripts as easy to read as possible. Using the five strategies you learned will greatly empower you to do this. Now its time to practice writing readable code.