In our last SQL post, we talked about creating temporary tables in SQL. In this post, we will explore how to add comments to SQL.
You will be able to add readability for not only yourself but others looking at your code.
After reading this you should be able to:
- Understand the importance of writing comments as part of your code.
- Describe several comment syntaxes.
- Write comments in your own code.
Why Add Comments.
Comments can help you remember what you were doing and why. Especially after long periods of working on something else.
They are also used to mute the expression of code.
Finally, comments can be used to troubleshoot query issues.
Adding Comments.
There are two ways to add comments. The first is to add a single-line comment and the second is to add a section comment.
Here is a single-line comment:
SELECT food_id,
- -food_type,
food_name
FROM foods
Here is a section comment:
SELECT food_id,
/*food_type,
food_name
*/
FROM foods
You can see that for a single-line comment you need two dashes ‘- -’.
On the other hand for a section comment, you need a forward slash followed by an asterisk and then in reverse to close the comment.
/* commented code
also commented code
also commented code.
*/
Source Code Editor.
Writing queries can get messy, especially when writing them directly to the database, there is often no formatting to help you define a structure for your code.
One way to overcome this is to use an IDE that highlights and indents statements for you so that you can easily code your queries. This will allow you to write more clean code quickly.